LINQ Where子句介紹
在向大家詳細(xì)介紹LINQ Where子句之前,首先讓大家了解下LINQ Where子句其實(shí)是用擴(kuò)展方法來(lái)實(shí)現(xiàn)的,然后全面介紹LINQ Where子句。
LINQ Where子句其實(shí)是用擴(kuò)展方法來(lái)實(shí)現(xiàn)的
微軟替我們實(shí)現(xiàn)的 LINQ Where子句對(duì)應(yīng)的擴(kuò)展函數(shù)實(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);
- }
- }
我們這個(gè)擴(kuò)展函數(shù)參數(shù):Func predicate 的定義看上面代碼的綠色delegate 代碼。
LINQ Where子句參數(shù)書寫的是Lambda 表達(dá)式
- (dd, aa) => dd.Length < aa 就相當(dāng)于 C# 2.0 的匿名函數(shù)。
LINQ中所有關(guān)鍵字比如 Select,SelectMany, Count, All 等等其實(shí)都是用擴(kuò)展方法來(lái)實(shí)現(xiàn)的。上面的用法同樣也適用于這些關(guān)鍵字子句。這個(gè)LINQ Where子句中Lambda 表達(dá)式第二個(gè)參數(shù)是數(shù)組索引,我們可以在Lambda 表達(dá)式內(nèi)部使用數(shù)組索引。來(lái)做一些復(fù)雜的判斷。具有數(shù)組索引的LINQ關(guān)鍵字除了Where還以下幾個(gè)Select,SelectMany, Count, All。
Select子句使用數(shù)組索引的例子
下面代碼有一個(gè)整數(shù)數(shù)組,我們找出這個(gè)數(shù)字是否跟他在這個(gè)數(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ù)組索引的例子
幾個(gè)句子組成的數(shù)組,我們希望把這幾個(gè)句子拆分成單詞,并顯示每個(gè)單詞在那個(gè)句子中。查詢語(yǔ)句如下:
- 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);
- }
【編輯推薦】