我數(shù)字與列表-使用什么?它們是如何工作的?我對枚舉器的工作方式和LINQ有一些疑問??紤]這兩個簡單的選擇:List<Animal> sel = (from animal in Animals
join race in Species
on animal.SpeciesKey equals race.SpeciesKey
select animal).Distinct().ToList();或IEnumerable<Animal> sel = (from animal in Animals
join race in Species
on animal.SpeciesKey equals race.SpeciesKey
select animal).Distinct();我更改了原始對象的名稱,使其看起來像一個更通用的示例。查詢本身并不那么重要。我想問的是:foreach (Animal animal in sel) { /*do stuff*/ }我注意到如果我用IEnumerable,當(dāng)我調(diào)試和檢查“sel”(在這種情況下是IEnDigable)時,它有一些有趣的成員:“innerKeySelector”、“innerKeySelector”和“outerKeySelector”,最后兩個成員似乎是委托?!皟?nèi)部”成員沒有“動物”實例,而是“物種”實例,這對我來說很奇怪?!巴獠俊背蓡T確實包含“動物”實例。我想是由兩位代表來決定哪些是進去的,哪些是從里面出來的?我注意到,如果使用“DISTISTION”,“Inside”包含6項(這是不正確的,因為只有2項是不同的),但是“外部”確實包含正確的值。同樣,可能是委托方法決定了這一點,但這比我對IEnDigable的了解要多一點。最重要的是,這兩種選擇中哪一種表現(xiàn)最好?通過.ToList()?或者直接使用枚舉器?如果可以的話,也請解釋一下或拋出一些鏈接來解釋IEnDigable的這種用法。
2 回答

不負相思意
TA貢獻1777條經(jīng)驗 獲得超10個贊
IEnumerable
foreach
foreach
List
IEnumerable
IEnumerable
.ToList()
foreach
IEnumerable
foreach
.ToList()
.
var things = from item in BigDatabaseCall() where .... select item;// this will iterate through the entire linq statement:int count = things.Count();// this will stop after iterating the first one, but will execute the linq againbool hasAnyRecs = things.Any();// this will execute the linq statement *again*foreach( var thing in things ) ...// this will copy the results to a list in memoryvar list = things.ToList()// this won't iterate through again, the list knows how many items are in itint count2 = list.Count();// this won't execute the linq statement - we have it copied to the listforeach( var thing in list ) ...
- 2 回答
- 0 關(guān)注
- 452 瀏覽
添加回答
舉報
0/150
提交
取消