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

【C#】干掉for循环

 2010-09-30 22:45:20 来源:WEB开发网   
核心提示: 注:无论是取奇数还是偶数,归根到底,【C#】干掉for循环(3),都是取一串东西中的某些东西,此时就用Where![Test]publicvoidOldMap(){int[]arr=new[]{0,1,2,3,4,5,6,7,8,9};List<int>new_list=newLis

注:无论是取奇数还是偶数,归根到底,都是取一串东西中的某些东西,此时就用Where!

    [Test]
    public void OldMap()
    {
      int[] arr = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
      List<int> new_list = new List<int>();
      for (int i = 0; i < arr.Length; i++)
      {
        new_list.Add(arr[i] * 10);
      }
      int[] new_arr = new_list.ToArray();
      Assert.That(new_arr, Is.EquivalentTo(new int[] { 0, 10, 20, 30, 40, 50, 60, 70, 80, 90 }));
    }
    [Test]
    public void NewMap()
    {
      int[] arr = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
      int[] new_arr = arr.Select(x => x * 10).ToArray();
      Assert.That(new_arr, Is.EquivalentTo(new int[] { 0, 10, 20, 30, 40, 50, 60, 70, 80, 90 }));
    }

注:无论是x10还是+99,归根到底,都是把一串东西变成一串新东西,此时就用Select!

    [Test]
    public void PrintMultiplicationFact()
    {
      Console.Write(
          " 1 x 1= 1  \n"
         + " 1 x 2= 2   2 x 2= 4  \n"
         + " 1 x 3= 3   2 x 3= 6   3 x 3= 9  \n"
         + " 1 x 4= 4   2 x 4= 8   3 x 4=12   4 x 4=16  \n"
         + " 1 x 5= 5   2 x 5=10   3 x 5=15   4 x 5=20   5 x 5=25  \n"
         + " 1 x 6= 6   2 x 6=12   3 x 6=18   4 x 6=24   5 x 6=30   6 x 6=36  \n"
         + " 1 x 7= 7   2 x 7=14   3 x 7=21   4 x 7=28   5 x 7=35   6 x 7=42   7 x 7=49  \n"
         + " 1 x 8= 8   2 x 8=16   3 x 8=24   4 x 8=32   5 x 8=40   6 x 8=48   7 x 8=56   8 x 8=64  \n"
         + " 1 x 9= 9   2 x 9=18   3 x 9=27   4 x 9=36   5 x 9=45   6 x 9=54   7 x 9=63   8 x 9=72   9 x 9=81  \n"
      );
      /*********************方法一: 嵌套循环*************************/
      for (int j = 1; j < 10; j++)
      {
        for (int i = 1; i < 10; i++)
        {
          if (i <= j)
          {
            Console.Write("{0, 2} x{1, 2}={2, 2}\t", i, j, i * j);
          }
        }
        Console.Write("\n");
      }
      /*********************方法二: 扩展方法*************************/
      Enumerable.Range(1, 9)
          .SelectMany(j => Enumerable.Range(1, 9), (j, i) => new { i, j })
          .Where(x => x.i <= x.j)
          .GroupBy(x => x.j)
          .Select(g => g.Aggregate("", (a, x) => a + string.Format("{0, 2} x{1, 2}={2, 2}\t", x.i, x.j, x.i * x.j)))
          .ToList().ForEach(x => Console.WriteLine(x));
      /*********************方法三: Linq表达式************************/
      (
        from j in Enumerable.Range(1, 9)
        from i in Enumerable.Range(1, 9)
        where i <= j
        group new { i, j } by j into g
        select new
        {
          LineNo = g.Key,
          Line = g.Aggregate("", (a, x) => a + string.Format("{0, 2} x{1, 2}={2, 2}\t", x.i, x.j, x.i * x.j))
        }
      ).ToList().ForEach(g => Console.WriteLine(g.Line));
    }

上一页  1 2 3 4  下一页

Tags:干掉 for 循环

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接