熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

【C#】干掉for循環

2013-11-13 10:07:32  來源: .NET編程 

  在C系列語言中for循環扮演著重要的角色很難想象一百行C代碼裡面沒有一個for循環(我有個朋友寫了個幾千行的算法沒有用的for循環我當時很驚訝)就好比一百行中文裡面沒有一個可見for循環是代碼的基本構造塊由於for循環一般是用來對一串類型相同的對象進行操作的從側面可以看出它經常伴隨著數組而來的用比較通俗的話說for循環數組是黃金搭檔 

  在裡面引進了foreach循環它與for循環本質是相同的由於在foreach循環中省去了指標i(常常只用來取第i個項別無他用)很多人欣然接受了foreach循環畢竟沒有奪走for循環它還在!

  編程語言一直在進化先後經歷了語言過程式語言面向對象語言總體來說越來越高級越來越抽象當代程序員可以不知道是啥就可以編程調用一個sort方法就排序了不知道用的是冒泡還是快速排序算法(外國人都幫我們弄好了!每當認識到差距超過這個事實我都好了不想傷心事了!)

  在C# 引進了Extension Methods伴隨而來的是一個新玩意兒Linq用實用工具Reflectorexe打開SystemCoredll中的 SystemLinq命名空間有個Enumerable靜態類其中有大量的對數組操作的擴展方法(你能想到的基本都有不信就去看看!)

  對於用慣了for循環的朋友如果要他/她停止使用肯定會覺得日子沒法過了放心好了我不會勸他/她停止使用的就像戒煙一樣都是自己的事(又一次跑題言歸正傳!)

  下面我用代碼來演示如何用擴展方法/Linq來干掉for循環

  注對於嵌套的for循環就用SelectMany!

  聲明for循環很好你可以繼續用如果你想用的話如果你喜歡嘗試新東西我想告訴你:這也許是應該的!

  附錄乘法口訣

    x =   
  x =     x =   
  x =     x =     x =   
  x =     x =     x =    x =  
  x =     x =    x =    x =    x =  
  x =     x =    x =    x =    x =    x =  
  x =     x =    x =    x =    x =    x =    x =  
  x =     x =    x =    x =    x =    x =    x =    x =  
  x =     x =    x =    x =    x =    x =    x =    x =    x =  

  附錄完整代碼

  代碼

  using System;
using SystemCollectionsGeneric;
using SystemLinq;
using SystemText;
using NUnit;
namespace KSharp
{
  [TestFixture]
  public class TestForLoop
  {
    [Test]
    public void OldSum()
    {
      int sum = ;
      for (int i = ; i < ; i++)
      {
        sum += i;
      }
      AssertAreEqual( sum);
    }
    [Test]
    public void NewSum()
    {
      int sum = EnumerableRange( )Sum();
      int sum = EnumerableRange( )Aggregate((x y) => x + y);
      int sum = EnumerableRange( )Aggregate( (x y) => x + y);
      AssertAreEqual( sum);
      AssertAreEqual( sum);
      AssertAreEqual( sum);
    }
    [Test]
    public void OldFilter()
    {
      int[] arr = new[] {           };
      List<int> odd_list = new List<int>();
      for (int i = ; i < arrLength; i++)
      {
        if (arr[i] %  == )
        {
          odd_listAdd(arr[i]);
        }
      }
      int[] odd_arr = odd_listToArray();
      AssertThat(odd_arr IsEquivalentTo(new int[] {      }));
    }
    [Test]
    public void NewFilter()
    {
      int[] arr = new[] {           };
      int[] odd_arr = arrWhere(x => x %  == )ToArray();
      AssertThat(odd_arr IsEquivalentTo(new int[] {      }));
    }
    [Test]
    public void OldMap()
    {
      int[] arr = new[] {           };
      List<int> new_list = new List<int>();
      for (int i = ; i < arrLength; i++)
      {
        new_listAdd(arr[i] * );
      }
      int[] new_arr = new_listToArray();
      AssertThat(new_arr IsEquivalentTo(new int[] {           }));
    }
    [Test]
    public void NewMap()
    {
      int[] arr = new[] {           };
      int[] new_arr = arrSelect(x => x * )ToArray();
      AssertThat(new_arr IsEquivalentTo(new int[] {           }));
    }

    [Test]
    public void PrintMultiplicationFact()
    {
      ConsoleWrite(
            x =   \n
         +   x =     x =   \n
         +   x =     x =     x =   \n
         +   x =     x =     x =    x =  \n
         +   x =     x =    x =    x =    x =  \n
         +   x =     x =    x =    x =    x =    x =  \n
         +   x =     x =    x =    x =    x =    x =    x =  \n
         +   x =     x =    x =    x =    x =    x =    x =    x =  \n
         +   x =     x =    x =    x =    x =    x =    x =    x =    x =  \n
      );
      /*********************方法一: 嵌套循環*************************/
      for (int j = ; j < ; j++)
      {
        for (int i = ; i < ; i++)
        {
          if (i <= j)
          {
            ConsoleWrite({ } x{ }={ }\t i j i * j);
          }
        }
        ConsoleWrite(\n);
      }
      /*********************方法二: 擴展方法*************************/
      EnumerableRange( )
          SelectMany(j => EnumerableRange( ) (j i) => new { i j })
          Where(x => xi <= xj)
          Grouy(x => xj)
          Select(g => gAggregate( (a x) => a + stringFormat({ } x{ }={ }\t xi xj xi * xj)))
          ToList()ForEach(x => ConsoleWriteLine(x));
      /*********************方法三: Linq表達式************************/
      (
        from j in EnumerableRange( )
        from i in EnumerableRange( )
        where i <= j
        group new { i j } by j into g
        select new
        {
          LineNo = gKey
          Line = gAggregate( (a x) => a + stringFormat({ } x{ }={ }\t xi xj xi * xj))
        }
      )ToList()ForEach(g => ConsoleWriteLine(gLine));
    }
  }
}


From:http://tw.wingwit.com/Article/program/net/201311/12625.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.