Linq學習筆記3

2022-07-25 19:09:15 字數 2249 閱讀 9232

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

public delegate t func();

public delegate t func(a0 arg0);

public delegate t func(a0 arg0,a1 arg1);

public delegate t func(a0 arg0,a1 arg1,a2 arg2);

public delegate t func(a0 arg0,a1 arg1,a2 arg2,a3 arg3);

enumerable類中的許多擴充套件方法都接受這些delegate作為引數. 我們來看乙個linq的例子

var query = from d in

developers

where d.language == "c#"

select

d.name ;

//最終編譯器將上述轉化為

funcbool> filter = d=>d.language == "c#"

;func

string> selection= d=>d.name ;

ienumerable

query = developers.where(filter ).select(selection);

所有的linq 都可以轉化為 方法的形式

下面我們來學習system.linq下的所有方法

1. where:

//

方法宣告

public

static ienumerablewhere(this ienumerablesource, functionbool>predicate);

//public delegate t func(a0 arg0);

public

static ienumerablewhere(this ienumerablesource, functionint, bool> predicate);

//public delegate t func(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 ienumerableselect(t,s) (this ienumerablesource,funcselector);

public

static ienumerableselect(t,s) (this ienumerablesource,funcint,s>selector);

//selectmany方法宣告

public

static ienumerableselectmany(t,s) (this ienumerablesource,func>selector);

public

static ienumerableselectmany(t,s) (this ienumerablesource,funcint,ienumerable>selector);

public

static ienumerableselectmany(t,c,s) (this ienumerablesource,func> collectionselector , funcresultseletor);

select 與 selectmany 區別:

selectmany(t,c,s) 舉例:

var orders = customers.where(c=>c.country=="

italy")

. selectmany(c=>c.orders,

(c,o)=>new

);//

c=>c.orders 返回ienumerable

//c: customer

//o: order

var orders = from c in customers where c.country==

"italy

"from o in c.orders

select new

Linq學習筆記

有如下一段 db.employess 是table型別,而table型別繼承了iqueryable,net3.5中的擴充套件方法特性,在queryable中定義了select where 等一系列方法,這些方法跟linq查詢中的關鍵字select where 等對應,linq 查詢語句,編譯後最終形...

LINQ 學習筆記7

func delegates 函式 委託 func delegae的宣告 public delegate tr func public delegate tr func t0 a0 public delegate tr func t0 a0,t1 a1 public delegate tr func...

LinQ學習筆記(一)

查詢表示式必須以 from 子句開頭,並且必須以 select 或 group 子句結尾。在第乙個 from 子句和最後乙個 select 或 group 子句之間,查詢表示式可以包含乙個或多個下列可選子句 where orderby join let 甚至附加的 from 子句。還可以使用 int...