开发学院软件开发C语言 【C#】干掉for循环 阅读

【C#】干掉for循环

 2010-09-30 22:45:20 来源:WEB开发网   
核心提示: [Test]publicvoidOldSum(){intsum0=0;for(inti=0;i<10;i++){sum0+=i;}Assert.AreEqual(45,sum0);}[Test]publicvoidNewSum(){intsum1=Enumerable.Range(0,10

    [Test]
    public void OldSum()
    {
      int sum0 = 0;
      for (int i = 0; i < 10; i++)
      {
        sum0 += i;
      }
      Assert.AreEqual(45, sum0);
    }
    [Test]
    public void NewSum()
    {
      int sum1 = Enumerable.Range(0, 10).Sum();
      int sum2 = Enumerable.Range(0, 10).Aggregate((x, y) => x + y);
      int sum3 = Enumerable.Range(0, 10).Aggregate(0, (x, y) => x + y);
      Assert.AreEqual(45, sum1);
      Assert.AreEqual(45, sum2);
      Assert.AreEqual(45, sum3);
    }

注:无论是对一串数字求和还是求积,归根到底,都是把一串东西变成一个东西,此时就用Aggregate!

    [Test]
    public void OldFilter()
    {
      int[] arr = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
      List<int> odd_list = new List<int>();
      for (int i = 0; i < arr.Length; i++)
      {
        if (arr[i] % 2 == 1)
        {
          odd_list.Add(arr[i]);
        }
      }
      int[] odd_arr = odd_list.ToArray();
      Assert.That(odd_arr, Is.EquivalentTo(new int[] { 1, 3, 5, 7, 9 }));
    }
    [Test]
    public void NewFilter()
    {
      int[] arr = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
      int[] odd_arr = arr.Where(x => x % 2 == 1).ToArray();
      Assert.That(odd_arr, Is.EquivalentTo(new int[] { 1, 3, 5, 7, 9 }));
    }

上一页  1 2 3 4  下一页

Tags:干掉 for 循环

编辑录入:爽爽 [复制链接] [打 印]
[]
  • 好
  • 好的评价 如果觉得好,就请您
      0%(0)
  • 差
  • 差的评价 如果觉得差,就请您
      0%(0)
赞助商链接