LINQ Where子句介紹
在向大家詳細介紹LINQ Where子句之前,首先讓大家了解下LINQ Where子句其實是用擴展方法來實現(xiàn)的,然后全面介紹LINQ Where子句。
LINQ Where子句其實是用擴展方法來實現(xiàn)的
微軟替我們實現(xiàn)的 LINQ Where子句對應(yīng)的擴展函數(shù)實際是如下的定義:
- namespace System.Linq
- {
- public delegate TResult Func(TArg0 arg0, TArg1 arg1);
- public static class Enumerable
- {
- public static IEnumerable Where(this IEnumerable source, Func predicate);
- public static IEnumerable Where(this IEnumerable source, Func predicate);
- }
- }
我們這個擴展函數(shù)參數(shù):Func predicate 的定義看上面代碼的綠色delegate 代碼。
LINQ Where子句參數(shù)書寫的是Lambda 表達式
- (dd, aa) => dd.Length < aa 就相當(dāng)于 C# 2.0 的匿名函數(shù)。
LINQ中所有關(guān)鍵字比如 Select,SelectMany, Count, All 等等其實都是用擴展方法來實現(xiàn)的。上面的用法同樣也適用于這些關(guān)鍵字子句。這個LINQ Where子句中Lambda 表達式第二個參數(shù)是數(shù)組索引,我們可以在Lambda 表達式內(nèi)部使用數(shù)組索引。來做一些復(fù)雜的判斷。具有數(shù)組索引的LINQ關(guān)鍵字除了Where還以下幾個Select,SelectMany, Count, All。
Select子句使用數(shù)組索引的例子
下面代碼有一個整數(shù)數(shù)組,我們找出這個數(shù)字是否跟他在這個數(shù)組的位置一樣
- public static void LinqDemo01()
- {
- int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
- var numsInPlace = numbers.Select((num, index) =>
new { Num = num, InPlace = (num == index) });- Console.WriteLine("Number: In-place?");
- foreach (var n in numsInPlace)
- Console.WriteLine("{0}: {1}", n.Num, n.InPlace);
- }
SelectMany 子句使用數(shù)組索引的例子
幾個句子組成的數(shù)組,我們希望把這幾個句子拆分成單詞,并顯示每個單詞在那個句子中。查詢語句如下:
- public static void Demo01()
- {
- string[] text = { "Albert was here",
- "Burke slept late",
- "Connor is happy" };
- var tt = text.SelectMany((s, index) => from ss in s.Split(' ')
select new { Word = ss, Index = index });- foreach (var n in tt)
- Console.WriteLine("{0}:{1}", n.Word,n.Index);
- }
【編輯推薦】