內容來自《c#高效編程》
看完書忍不住感嘆,靠,Linq還能這樣用,NB
1 循環語句
int[] foo=new int[100];
for(int num=0;num<foo.Length;num++)
foo[num]=num*num;
foreach(int i in foo)
console.WriteLine(i.ToString());
2 查詢語句
int[] foo=(from n in Enumerable.Range(0,100)
select n*n).ToArray();
方法(1)中的打印語句,需要爲IEunmerable編寫一個擴展方法
public static class Extensions{
public static void ForAll<T>(
this IEunmerable<T> sequence,
Action<T> action)
{
foreach(T item in sequence)
action(item);
}
}
打印
foo.ForAll((n)=>Console.WriteLine(n.ToString());
3 應用場景
嵌套循環中使用linq查詢代替,能使表達更清晰、易讀。