Linq學習筆記3

想要了解Linq, 先必須知道System.Linq中定義的5個delegate

public delegate T Func<T>();

public delegate T Func<A0,T>(A0 arg0);

public delegate T Func<A0,A1,T>(A0 arg0,A1 arg1);

public delegate T Func<A0,A1,A2,T>(A0 arg0,A1 arg1,A2 arg2);

public delegate T Func<A0,A1,A2,A3,T>(A0 arg0,A1 arg1,A2 arg2,A3 arg3);

Enumerable類中的許多擴展方法都接受這些delegate作為參數. 我們來看一個linq的例子

var query = from d in developers
                   where d.Language == "C#"
                 select d.Name ; 
//最終編譯器將上述轉化為
Func<Developer,bool> filter = d=>d.Language == "C#";
Func<Developer,string> selection= d=>d.Name ;
IEnumerable<string> query = developers.Where(filter ).Select(selection);

所有的linq 都可以轉化為 方法的形式
下面我們來學習System.Linq下的所有方法

1. Where:

//方法聲明
public static Ienumerable<T> Where<T>(this Ienumerable<T> source, Function<T,bool> predicate);
 //public delegate T Func<A0,T>(A0 arg0);
public static Ienumerable<T> Where<T>(this Ienumerable<T> source, Function<T,int, bool> predicate);
//public delegate T Func<A0,A1,T>(A0 arg0,A1 arg1); 此處int 參數是source中以0開始的索引, 表示從哪個索引開始過濾
var query = customers.where((c,index)=>(c.Country=="Italy" && index >=1)).select(c=>c);

2. Select和SelectMany

//select 方法聲明
public static IEnumerable<S> Select(T,S) (this IEnumerable<T > source,Func<T,S> selector);
public static IEnumerable<S> Select(T,S) (this IEnumerable<T > source,Func<T,int,S> selector);
//selectMany方法聲明
public static IEnumerable<S> SelectMany(T,S) (this IEnumerable<T > source,Func<T,IEnumerable<S>> selector);
public static IEnumerable<S> SelectMany(T,S) (this IEnumerable<T > source,Func<T,int,IEnumerable<S>> selector);
public static IEnumerable<S> SelectMany(T,C,S) (this IEnumerable<T > source,Func<T,IEnumerable<C>> collectionSelector , Func<T,C,S> resultSeletor);

select 與 selectmany 區別:http://www.cnblogs.com/shawnliu/archive/2009/06/06/1497387.html

SelectMany(T,C,S) 舉例:

var orders = customers.where(c=>c.country=="Italy") 
                    . selectmany(c=>c.orders,
                     (c,o)=>new {o.Quantity,o.IdProduct});

//c=>c.orders 返回IEnumerable<Order>
//c: Customer
//o: Order
var orders = from c in customers where c.country=="Italy"
          from o in c.Orders
        select new {o.Quantity,o.IdProduct}

 

 

posted @ 2013-04-17 11:38  邪见  阅读(213)  评论(0)    收藏  举报