NET问答:Select 和 SelectMany 的区别
咨詢區
Tarik:
我已經 google 搜索了 Select 和 SelectMany 之間的區別,但我并沒有找到合適的答案,我現在急切的需要知道在 Linq to SQL 時兩者的區別而不是給我用Array展示...
能否有人幫忙提供 Linq To SQL 的例子嗎?
回答區
Mike Two:
SelectMany 它是對 列表中的列表 進行扁平化查詢,比如下面的例子。
public?class?PhoneNumber {public?string?Number?{?get;?set;?} }public?class?Person {public?IEnumerable<PhoneNumber>?PhoneNumbers?{?get;?set;?}public?string?Name?{?get;?set;?} }IEnumerable<Person>?people?=?new?List<Person>();//?Select?gets?a?list?of?lists?of?phone?numbers IEnumerable<IEnumerable<PhoneNumber>>?phoneLists?=?people.Select(p?=>?p.PhoneNumbers);//?SelectMany?flattens?it?to?just?a?list?of?phone?numbers. IEnumerable<PhoneNumber>?phoneNumbers?=?people.SelectMany(p?=>?p.PhoneNumbers);//?And?to?include?data?from?the?parent?in?the?result:? //?pass?an?expression?to?the?second?parameter?(resultSelector)?in?the?overload: var?directory?=?people.SelectMany(p?=>?p.PhoneNumbers,(parent,?child)?=>?new?{?parent.Name,?child.Number?});Sriwantha Attanayake:
SelectMany 類似 Sql 中的 cross join ,也就是所謂的笛卡爾積,比如下面的例子。
Set?A={a,b,c} Set?B={x,y}SelectMany 之后會得到如下結果。
{?(x,a)?,?(x,b)?,?(x,c)?,?(y,a)?,?(y,b)?,?(y,c)?}可以看出,上面就是羅列了 SetA 和 SetB 的所有組合,轉換成 linq 的話可以這么寫。
List<string>?animals?=?new?List<string>()?{?"cat",?"dog",?"donkey"?}; List<int>?number?=?new?List<int>()?{?10,?20?};var?mix?=?number.SelectMany(num?=>?animals,?(n,?a)?=>?new?{?n,?a?});輸出結果如下:
{(10,cat),?(10,dog),?(10,donkey),?(20,cat),?(20,dog),?(20,donkey)}AlejandroR:
De Gea
Alba
Costa
Villa
Busquets
點評區
很多時候,我發現越解釋概念越說不清楚,最后說著說著就把 理科 變成了 文科,把邏輯變成了硬記????????????,我覺得這時候啥也不要說,直接看源碼反而讓人更清楚是咋回事。。。
Select 的底層邏輯
SelectMany 的底層邏輯
不知道你是否 豁然開朗, 不明白的話,快用 ILSpy 去挖掘 Enumerable 吧!
原文鏈接:https://stackoverflow.com/questions/958949/difference-between-select-and-selectmany
總結
以上是生活随笔為你收集整理的NET问答:Select 和 SelectMany 的区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一日一技:ASP.NET Core 判断
- 下一篇: 龙芯3A5000完成流片 同主频性能追平