標籤:style blog color 使用 strong os
今天看了一些關於lambda運算式的知識,然後對於Func<T,TResult>泛型委派不太熟悉,便查了查相關資料,又引出來了基於謂詞篩選值序列這個對我來說的新鮮知識點,於是去查MSDN,以下是看到的一些相關介紹:
此方法通過使用順延強制實現。 即時傳回值為一個對象,該Object Storage Service執行操作所需的所有資訊。 只有通過直接調用對象的 GetEnumerator 方法或使用 Visual C# 中的 foreach(或 Visual Basic 中的 For Each)來枚舉該對象時,才執行此方法表示的查詢。
在查詢運算式文法中,where (Visual C#) 或 Where (Visual Basic) 子句轉換為 Where<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>) 的一個調用。
List<string> fruits = new List<string> { "apple", "passionfruit", "banana", "mango", "orange", "blueberry", "grape", "strawberry" }; IEnumerable<string> query = fruits.Where(fruit => fruit.Length < 6); foreach (string fruit in query) { Console.WriteLine(fruit); }
上面這段代碼的輸出結果:
applemangogrape
上面是一個簡單地樣本,接下來看一個稍微複雜的,直接上代碼了:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace LambdaTest{ class Program { static void Main(string[] args) { List<int> list = new List<int>(); list.AddRange(new int[] { 7, 6, 10, 1, 2, 3, 4, 5, 8 }); Func<int, bool> fi = new Func<int, bool>(MoreThan5); IEnumerator<int> ie = list.Where<int>(fi).GetEnumerator(); //效果與list.Where<int>(fi).GetEnumerator()一致 //IEnumerator<int> ie = list.Where<int>(x => x > 5).GetEnumerator(); //效果與list.Where<int>(fi).GetEnumerator()一致 //IEnumerator<int> ie = list.Where(delegate(int i){return i > 5;}).GetEnumerator(); while (ie.MoveNext()) { Console.WriteLine(ie.Current.ToString()); } Console.ReadKey(); } public static bool MoreThan5(int i) { return i > 5; } }}
上面這段代碼的輸出結果:
7
6
10
8
其中用到了IEnumerator和泛型以及委託的相關知識,希望可以作為引子,給大家帶來一點新的趕腳~~