天天看點

最全面Enumerable類的實用總結

ALL方法判斷序列元素是否滿足條件,如果滿足條件則傳回true’;否則傳回false,該方法文法如下:

public static bool All<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);

   參數:

    Source:包含要應用謂詞的元素的 System.Collections.Generic.IEnumerable<T>。

    predicate:     用于測試每個元素是否滿足條件的函數。

類型參數:  TSource: source 中的元素的類型。

      傳回結果: 如果源序列中的每個元素都通過指定謂詞中的測試,或者序列為空,則為 true;否則為 false。

public partial class Frm_Main : Form

   {

       public Frm_Main()

       {

           InitializeComponent();

       }

       private void Frm_Main_Load(object sender, EventArgs e)

           List<Person> People = new List<Person>//建立人員清單

           new Person(1,"王*軍",28),

           new Person(2,"趙*東",31),

           new Person(3,"王*科",33)

       };

           bool result = People.All(p => p.Old > 30);//判斷是否所有人員的年齡都大于30歲

           label3.Text = "查詢結果:" + result.ToString();//查詢結果

輸出結果:false

   }

   public class Person

       public Person(int id, string name, int old)

           this.ID = id;

           this.Name = name;

           this.Old = old;

       public int ID { get; set; }//人員ID

       public string Name { get; set; }//人員名稱

       public int Old { get; set; }//年齡

使用Count也可以實作相同的功能:

bool result=People.Count(p=>p.Old>=30)==People.Count();

使用ElementAt方法擷取指定位置的元素,文法:

public static TSource ElementAt<TSource>(this IEnumerable<TSource> source, int index);

參數:

 source: 要從中傳回元素的 System.Collections.Generic.IEnumerable<T>。

index:  要檢索的從零開始的元素索引。

傳回結果:  源序列中指定位置處的元素。

例:List<int> ints=new List<int>({0,1,2,3,4,5,6}); int result=ints.ElementAt(3);

Repeat方法用來生成一個重複值的序列

文法格式:

public static IEnumerable<TResult> Repeat<TResult>(TResult element, int count);

element:要重複的值。Count:在生成序列中重複該值的次數。

傳回值:一個IEnumerable<T>:包含一個重複值。

例:string[] strA=Enumerable.Repeat<String>(“lsj”,3).ToArray();//初始化長度為3的字元串數組,所有的元素之為”lsj”

Range方法:Enumerable類的Range方法用來生成指定範圍的整數序列,文法格式:

 public static IEnumerable<int> Range(int start, int count);

start:序列中一個整數的值。Count:要生成的順序整數的數組。

傳回值:IEnumerable<Int32>數型值。

例:int[] intA=Enumerable.Range(0,3).ToArray<int>();//長度為3,元素值:0,1,2

int[] intB=Enumerable.Range(0,5).Select(i=>i*10).ToArray<int>();//元素值為:0,10,20,30,40

ConCat方法:用來連接配接兩個序列,文法如下:  public static IEnumerable<TSource> Concat<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second);

參數說明:first:要連接配接的一個序列,second:要與一個序列連接配接的序列。

傳回值:一個IEnumerable<T>,包含兩個輸入序列的連接配接元素。

例:string[] str3=str1.Concat(str2);

OfType方法:用來根據指定類型篩選序列中的元素,文法如下:

public static IEnumerable<TResult> OfType<TResult>(this IEnumerable source);

參數說明:TResult篩選序列元素所指定的類型。Source:IEnumerable類型的源序列。傳回值:隻傳回元素是TResult類型的序列。

例:ArrayList arr=new ArrayList(); arrList.Add(1);arrList.Add(2);arrList.Add(3);arrList.Add(“A”);arrList.Add(“b”);

     var query=from item in arrList.OfType<string>() select item;

      結果:A b

Jion方法:用來基于比對鍵對兩個序列的元素進行關聯,使用預設的相等比較器對鍵進行比較,其文法如下:  public static IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>(this IEnumerable<TOuter> outer, IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, TInner, TResult> resultSelector);

          outer:要聯接的第一個序列。

 inner:要與第一個序列聯接的序列。

          outerKeySelector: 用于從第一個序列的每個元素提取聯接鍵的函數。innerKeySelector:用于從第二個序列的每個元素提取聯接鍵的函數。

resultSelector:用于從兩個比對元素建立結果元素的函數。

       類型參數:  TOuter:   第一個序列中的元素的類型。

 TInner: 第二個序列中的元素的類型。

  TKey:   鍵選擇器函數傳回的鍵的類型。

  TResult:  結果元素的類型。

       傳回結果:  一個具有 TResult 類型元素的 System.Collections.Generic.IEnumerable<T>,這些元素是通過對兩個序列執行内部聯接得來的。

例:public partial class Frm_Main : Form

           List<SaleBill> bills = new List<SaleBill>//建立銷售單清單

           new SaleBill("XS001","王*科",Convert.ToDateTime("2010-1-1")),

           new SaleBill("XS002","王*軍",Convert.ToDateTime("2010-2-1")),

           new SaleBill("XS003","趙*東",Convert.ToDateTime("2010-3-1"))

           List<SaleProduct> products = new List<SaleProduct>//建立銷售商品清單

           new SaleProduct("XS001","冰箱",1,2000),

           new SaleProduct("XS001","洗衣機",2,600),

           new SaleProduct("XS002","電暖風",3,50),

           new SaleProduct("XS002","吸塵器",4,200),

           new SaleProduct("XS003","手機",1,990)

           //關聯銷售單清單和銷售商品清單      

           var query= bills.Join(products,

                              b => b.SaleBillCode,

                              p => p.SaleBillCode,

                              (b, p) => new

                              {

                                  銷售單号 = b.SaleBillCode,

                                  銷售日期 = b.SaleDate,

                                  銷售員 = b.SaleMan,

                                  商品名稱 = p.ProductName,

                                  數量 = p.Quantity,

                                  單價 = p.Price,

                                  金額 = p.Quantity * p.Price

                              });

           dataGridView1.DataSource = query.ToList();//資料綁定

   class SaleBill//銷售單據類

       public SaleBill(string saleBillCode, string saleMan, DateTime saleDate)

           this.SaleBillCode = saleBillCode;

           this.SaleMan = saleMan;

           this.SaleDate = saleDate;

       public string SaleBillCode { get; set; }//銷售單号

       public string SaleMan { get; set; }//銷售員

       public DateTime SaleDate { get; set; }//銷售日期

   class SaleProduct//銷售商品類

       public SaleProduct(string saleBillCode, string productName, int quantity, double price)

           this.ProductName = productName;

           this.Quantity = quantity;

           this.Price = price;

       public string ProductName { get; set; }//商品名稱

       public int Quantity { get; set; }//數量

       public double Price { get; set; }//單價

}

輸出結果:

最全面Enumerable類的實用總結

IsUpper方法用來指定的Unicode字元是否屬于大寫字母類别,文法如下:

public static bool IsUpper(char c)

c:System.Char類型,一個Unicode字元。

傳回值:如果c是大寫字母,則為true,否則為false。

例:var query=from s in sourceString where char.IsUpper(s) select s;

IsLetter方法可以過濾字元串中屬于字母類别的字元,例:

var query=from s in sourceString where char.IsLetter(s) select s;

IsDigit方法用來訓示字元串是否屬于十進制數字類别。

Var query=from s in sourceString where char.IsDigit(s) select s;

IsControl方法可以過濾字元串中的控制字元串,例:

Var query =from s in sourceString where char.IsControl(s) select s;

IsLower方法可以過濾字元串中屬于小寫字母的名稱,例:

 Var query=from s in sourceString where char.IsLower(s) select s;

Aggregate方法用來堆積和中的元素進行自定義的聚合計算,其文法格式如下:

public static TResult Aggregate<TSource, TAccumulate, TResult>(this IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func, Func<TAccumulate, TResult> resultSelector);

參數:

TSource: source 中的元素的類型。

source:IEnumerable<TSource>類型。

func:System.Func<TSource,TSource,TSource>類型,拜師對每個元素調用的累加器函數。

傳回值:TSource 類型,累加器的最終值。

例:

     DataClassesDataContext dc = new DataClassesDataContext();//建立LINQ對象

           //将銷售商品明細表中的金額字段值取出,并轉換為數組

           double[] amountArray = dc.V_SaleDetail.Select(itm => itm.amount).ToArray<double>();

           double amountSum = amountArray.Aggregate((a, b) => a + b);//計算商品銷售總額

//等效于:  double amountSum = amountArray.Sum();

AsEnumerable方法,用來将資料源轉換為IEnumerable<T>類型,文法如下:

public static IEnumerable<TSource> AsEnumerable<TSource>(this IEnumerable<TSource> source);

參數說明:TSource:source中的元素的類型。

source:類型為IEnumerable<TSource>的資料源。

傳回值:傳回類型為IEnumerable<TSource>的序列。

 List<Person> People = new List<Person>();//建立List泛型對象

           for (int i = 1; i < 10; i++)

           {

               People.Add(new Person(i, "User0" + i.ToString()));//添加項

           }

   var query = from p in People.AsEnumerable<Person>()//轉換為IEnumerable<Person>類型

                       where p.ID < 4

                       select new

                       {

                           ID = p.ID,

                           Name = p.Name

                       };

           foreach (var item in query)

               label1.Text += item + "\n";//顯示資訊

注:将List對象轉換為T[]類型,代碼如下:Person[] perArr=People.ToArray();

将List轉換為字典類型:Dictionary<int,Person> dict=People.ToDictionary(item=>item.ID);

ToList方法:用來産品賣給IEnumerable<TSource>類型的執行個體對象建立一個List<TSource>類型的對象,其文法格式如下:public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source);

TSource:source中的元素的類型

Source:IEnumerable<TSource>類型的執行個體對象。

傳回值:建立的List<T>類型的對象。

  //構造List<UserInfo>泛型清單

           List<UserInfo> users = new List<UserInfo> {

           new UserInfo{UserCode=1, UserName="User001", Password="001"},

           new UserInfo{UserCode=2, UserName="User002", Password="002"},

           new UserInfo{UserCode=3, UserName="User003", Password="003"},

           new UserInfo{UserCode=4, UserName="User004", Password="004"}};

           //使用LINQ查詢使用者名等于User001或密碼等于003的清單項

           //此時的query變量的類型是IEnumerable<UserInfo>類型

           var query = from item in users

                       where item.UserName == "User001" || item.Password == "003"

                       select item;

           //使用ToList方法将IEnumerable<UserInfo>類型轉換為List<UserInfo>類型

           List<UserInfo> filteredUsers = query.ToList<UserInfo>();

           //将泛型清單綁定DataGridView

           dataGridView1.DataSource = filteredUsers.ToList();

ToDictionary()方法将IEnumerable<TSource>類型的資料轉為Dictionary<TKey,TValue>類型的字典。

       var query = from item in users

                       where item.UserName.IndexOf("王") > -1

           //使用ToDictionary方法将query轉換為字典類型

            Dictionary<int, UserInfo> userDict = query.ToDictionary(itm => itm.UserCode);

           label1.Text = "Dictionary的結果是:\n";

           foreach (var user in userDict)

               string temp = string.Format("(Key:{0},Value:{1})", user.Key, user.Value.UserName);

               label1.Text += temp + "\n";

當Value為基本資料類型是,例為String類型是,要指定轉化的字段。上述例可以改為:    Dictionary<int, string> userDict = query.ToDictionary(itm => itm.UserCode,r=>r.UserName);

               string temp = string.Format("(Key:{0},Value:{1})", user.Key, user.Value);

ToLookup方法:Enumerable類的ToLookup方法用來按鍵值将源序列中的元素放入一對多的字典序列,其文法如下:        //

public static ILookup<TKey, TSource> ToLookup<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);

參數說明:

      TKey:keySelector傳回的鍵類型。

      TSource:source中的元素類型。

      source:IEnumerable<TSource>類型的源序列,将從它建立一個Lookup<TKey,TValue>類型的一對多字典。

      keySelector System.Func<TSource,TKey>類型,用于每個元素中提取鍵的函數

      傳回值: 一個包含鍵和值得Lookup<TKey,TValue>

   //構造泛型清單

           new UserInfo{UserCode=1, UserName="User002", Password="002"},

           new UserInfo{UserCode=2, UserName="User003", Password="003"},

           new UserInfo{UserCode=2, UserName="User004", Password="004"}};

           //使用LINQ查找使用者代碼小于3的清單

                       where item.UserCode < 3

           //使用ToLookup方法将query轉換為一對多字典類型,注意傳回的是接口

           ILookup<int, UserInfo> userLookup = query.ToLookup(itm => itm.UserCode);

           label1.Text = "ILookup的結果是:\n";

           foreach (var user in userLookup)//周遊查詢結果

               label1.Text += user.Key;//顯示主鍵

               label1.Text += "   ";

               foreach (var user2 in user)//周遊所有值

               {

                   label1.Text += user2.UserName + " , ";//顯示鍵值

               }

               label1.Text += "\n";

最全面Enumerable類的實用總結

注:實作ILookup的排序:

Var ord= userLookup.OrderByDescending(r=>r.key);

Cast方法:用來将IEnumerable的元素轉換為指定的類型,其文法格式如下:

     public static IEnumerable<TResult> Cast<TResult>(this IEnumerable source);

    參數說明:

      TResult:source中的元素要轉換成的類型。

         source:包含要轉換的元素的IEnumerable

         傳回值:一個IEnumerable<T> ,包含已轉換為指定類型的源序列的每個元素。

  string[] strs = { "Mary", "Rose", "Jack", "Peter" };//定義字元串數組

IEnumerable<string> strIESource = strs.Select(i => i.Substring(0, 3));//擷取字元串序列

IEnumerable<object> objIEResult = strIESource.Cast<object>();//把字元串序列轉為IEnumerable<object>

     foreach (object item in objIEResult)//周遊輸出IEnumerable<object>序列

      {

         Console.WriteLine(item.ToString());

          }

第一種:轉換為序列:

 IEnumerable<string> strIESource = strs.Select(i => i);//擷取字元串序列

           List<string> strListSource = new List<string>(strIESource);//執行個體化List<string>

           第一種寫法:List<object> objListResult = new

List<object>(strListSource.Cast<object>());//把List<string>轉換為List<object>

           第二種寫法:   List<object> objListResult = strListSource.Cast<object>().ToList();    //把List<string>轉換為List<object>

           Console.WriteLine("把List<string>轉換為List<object>的運作結果:");

           foreach (object item in objListResult)//周遊輸出List<object>集合

               Console.WriteLine(item.ToString());

第二種轉換:将List<string>轉換為List<object>的運作結果

Linq應用舉例:

使用Repeat建立随機數生成器

     static void Main(string[] args)

           Random rand = new Random();//建立一個随機數生成器

           Console.WriteLine("請輸入一個整數:");

           try

               int intCount = Convert.ToInt32(Console.ReadLine());//輸入要生成随機數的組數

               //生成一個包含指定個數的重複元素值的序列,

               //由于Linq的延遲性,是以此時并不産生随機數,而是在枚舉randomSeq的時候生成随機數

               IEnumerable<int> randomSeq = Enumerable.Repeat<int>(1, intCount).Select(i => rand.Next(1,100));

               Console.WriteLine("将産生" + intCount.ToString() + "個随機數:");

               foreach (int item in randomSeq)//通過枚舉序列來生成随機數,

                   Console.WriteLine(item.ToString());//輸出若幹組随機數

請輸入一個整數:

5

将産生5個随機數:

78

47

88

95

51

           catch (Exception ex)

               Console.WriteLine(ex.Message);

           Console.Read();

使用Concat連接配接兩個數組

 static void Main(string[] args)

           Program p = new Program();//建立Program對象,用來調用類的方法

           string[] P_str_Name = { "C#程式設計全能詞典", "C#程式設計詞典個人版", "C#程式設計詞典企業版" };      //定義字元串數組

           string[] P_str_Money = { "98元", "698元", "2998元" };//定義字元串數組

           Console.WriteLine("這兩組數組的元素:");

           p.TestB(P_str_Name, P_str_Money);//調用方法輸出兩個數組中的所有元素

       //該方法實作連接配接兩個字元串,并輸出所有的元素

       private void TestB(string[] str1s, string[] str2s)

       {//第一種周遊方式,使用ForEach:

str1s.Concat<string>(str2s).ToList().ForEach(p => Console.Write(p+"  "));

           foreach (string item in str1s.Concat<string>(str2s))//數組str1s與數組str2s連接配接,然後周遊,正常的便利方式

               Console.Write(item + "  ");

這兩組數組的元素:

C#程式設計全能詞典  C#程式設計詞典個人版  C#程式設計詞典企業版  98元  698元  2998元

按照開始字母的條件,找出單詞

string[] strings = { "A penny saved is a peny earned.", "The early bird catches the worm.", "The pen is mightier than the sword" };

           var earlyBirdQuery = from sentence in strings let words = sentence.Split(' ') from word in words let w = word.ToLower()

                                where w[0] == 'a' || w[0] == 'e' || w[0] == 'i' || w[0] == 'o' || w[0] == 'u' select word;

           foreach (var v in earlyBirdQuery)

               Console.WriteLine("\"{0}\" Start with a vowel",v);

"A" Start with a vowel

"is" Start with a vowel

"a" Start with a vowel

"earned." Start with a vowel

"early" Start with a vowel

從一篇英文文章中找出所有的單詞,并統計單詞的重複次數。

     public partial class Frm_Main : Form

           //聲明字元串

           string text = @"var query = from info in infoList

   where info.AuditFlag == null || info.AuditFlag == false

   join emp in empList

      on info.SaleMan equals emp.EmployeeCode

   join house in houseList

      on info.WareHouse equals house.WareHouseCode

   join client in clientList

      on info.ClientCode equals client.ClientCode

   join dictPayMode in dictList

      on info.PayMode equals dictPayMode.ValueCode

   where dictPayMode.TypeCode == 'PayMode\'

   join dictInvoiceType in dictList

      on info.InvoiceType equals dictInvoiceType.ValueCode

   where dictInvoiceType.TypeCode == 'InvoiceType'

   select new

      id = info.ID,

      SaleBillCode = info.SaleBillCode,

      SaleMan = emp.Name,

      SaleDate = info.SaleDate,

      Provider = client.ShortName,

      WareHouse = house.ShortName,

      PayMode = dictPayMode.ValueName,

      InvoiceType = dictInvoiceType.ValueName,

      InvoiceCode = info.InvoiceCode,

      AuditFlag = info.AuditFlag

   };";

    //按單詞轉換為數組

 string[] allWords = (from n in System.Text.RegularExpressions.Regex.Split(text, "[^A-Za-z]") let word = n.ToLower() where word.Length > 0 select n).ToArray();

string[] distinctWords = allWords.Distinct().ToArray<string>();//去掉單詞數組中重複的單詞

// 第一種方式

 int[] counts = new int[distinctWords.Length];//建立一個存放詞頻統計資訊的數組

       for (int i = 0; i < distinctWords.Length; i++)//周遊每個單詞

        {

          string tempWord = distinctWords[i];

          var query = from item in allWords where item.ToLower() == tempWord.ToLower()  select item; //計算每個單詞出現的次數

               counts[i] = query.Count();

           //輸出詞頻統計結果

           for (int i = 0; i < counts.Count(); i++)

               label1.Text+=distinctWords[i] + "出現 " + counts[i].ToString() + " 次\n";

      }

//第二種方式:将結果儲存為鍵值對的形式

Dictionary<string, int> dicQuery = queryList.ToDictionary(r => r.key, r => r.keyCount);

           dicQuery.ToList().ForEach(r => label1.Text += r.Key + "出現" + r.Value + "次\n");

List<string> wordList = new List<string>(distinctWords);

           List<string> allWordList = new List<string>(allWords);

           var queryList = from word in wordList

                           select new

                           {

                               key = word,

                               keyCount = allWordList.Count(p => p == word)

                           };

           foreach (var query in queryList)

               label1.Text += query.key + "出現:" + query.keyCount + "次\n";

           }//周遊方式,可以改為如下:

}

groupBy字句實作元素按長度分組,group字句用于對查詢的結果進行分組,并傳回一個IGrouping<TKey,TElment>對象序列,by字句表示按指定條件進行分組,如本執行個體中按照元素的長度進行分組;into 字句可以建立一個曆史辨別符,使用該符号可以存儲group、join或Select字句的結果。例:

           string[] Words = new string[] { "what", "is", "your", "name", "?", "my", "name", "is", "lyf", "." };

           var Groups = from word in Words

           group word by word.Length into lengthGroups//按單詞長度将單詞分組

                    orderby lengthGroups.Key descending//按單詞長度降序排列

           select new

            {

               Length = lengthGroups.Key,//取單詞長度

               WordCollect = lengthGroups//取該長度的單詞分組集合

            };

  foreach (var group in Groups)//周遊每組單詞

  {

      label1.Text +="包含" + group.Length.ToString() + "個字元的單詞有:" + "\n";

      foreach (string word in group.WordCollect)

           label1.Text +="    " + word + ",";

      label1.Text +="\n" ;

    }

  }

最全面Enumerable類的實用總結

join 和join into的差別。

public struct Users

       private string name;

       private int id;

       public string Name

           get { return name; }

       public int Id

           get { return id; }

       public Users(string name, int id)

           this.name = name;

           this.id = id;

   public struct Order

       private float money;

       public int Id { get { return id; } }

       public float Money { get { return money; } }

       public Order(int id, float money)

           this.money = money;

   class Program

   {    

       static void Main(string[] args)

           Users[] us=new Users[]{new Users("王某",001),new Users("蔡某",002),new Users("劉某",003)};

           Order[] od = new Order[] { new Order(001, 130), new Order(002, 510), new Order(003, 200), new Order(001, 1022), new Order(003, 355) };

           var join = us.Join(od, u => u.Id, o => o.Id, (u, o) => new { u.Id, u.Name, o.Money });

           Console.WriteLine("使用Join方法連接配接結果如下:");

           foreach (var item in join)

               Console.WriteLine(item);

           var join_into = from u in us

                           join o in od on u.Id equals o.Id

                               into userOrder

                           select new { u.Name, Num = userOrder.Count() };

           Console.WriteLine("使用Join into子句連接配接結果如下:");

           foreach (var item in join_into)

使用Join方法連接配接結果如下:

{ Id = 1, Name = 王某, Money = 130 }

{ Id = 1, Name = 王某, Money = 1022 }

{ Id = 2, Name = 蔡某, Money = 510 }

{ Id = 3, Name = 劉某, Money = 200 }

{ Id = 3, Name = 劉某, Money = 355 }

使用Join into子句連接配接結果如下:

{ Name = 王某, Num = 2 }

{ Name = 蔡某, Num = 1 }

{ Name = 劉某, Num = 2 }

繼續閱讀