我数字与列表-使用什么?它们是如何工作的?

我数字与列表-使用什么?它们是如何工作的?

我对枚举器的工作方式和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*/ }
  1. 我注意到如果我用IEnumerable,当我调试和检查“sel”(在这种情况下是IEnDigable)时,它有一些有趣的成员:“innerKeySelector”、“innerKeySelector”和“outerKeySelector”,最后两个成员似乎是委托。“内部”成员没有“动物”实例,而是“物种”实例,这对我来说很奇怪。“外部”成员确实包含“动物”实例。我想是由两位代表来决定哪些是进去的,哪些是从里面出来的?

  2. 我注意到,如果使用“DISTISTION”,“Inside”包含6项(这是不正确的,因为只有2项是不同的),但是“外部”确实包含正确的值。同样,可能是委托方法决定了这一点,但这比我对IEnDigable的了解要多一点。

  3. 最重要的是,这两种选择中哪一种表现最好?

通过.ToList()?

或者直接使用枚举器?

如果可以的话,也请解释一下或抛出一些链接来解释IEnDigable的这种用法。


守着一只汪
浏览 396回答 2
2回答

POPMUISE

这里有一篇很好的文章:克劳迪奥·伯纳斯科尼的TechBlog:何时使用IEnumber,IC,IList和List

不负相思意

实现的类IEnumerable允许您使用foreach语法。基本上,它有一个方法来获取集合中的下一个项。它不需要整个集合在内存中,也不知道其中有多少项,foreach一直拿到下一件直到用完为止。在某些情况下,这可能非常有用,例如,在大规模数据库表中,在开始处理行之前,您不希望将整个事件复制到内存中。现在List实施器IEnumerable,但表示内存中的整个集合。如果你有IEnumerable然后你打电话.ToList()创建一个新列表,其中包含内存中枚举的内容。Linq表达式返回枚举,默认情况下,当您使用foreach..阿IEnumerable循环时执行Linq语句。foreach,但您可以强制它更快地使用.ToList().我的意思是:var&nbsp;things&nbsp;=&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;from&nbsp;item&nbsp;in&nbsp;BigDatabaseCall() &nbsp;&nbsp;&nbsp;&nbsp;where&nbsp;.... &nbsp;&nbsp;&nbsp;&nbsp;select&nbsp;item;//&nbsp;this&nbsp;will&nbsp;iterate&nbsp;through&nbsp;the&nbsp;entire&nbsp;linq&nbsp;statement:int&nbsp;count&nbsp;=&nbsp;things.Count();//&nbsp;this&nbsp;will&nbsp;stop&nbsp;after&nbsp;iterating&nbsp;the&nbsp;first&nbsp;one,&nbsp;but&nbsp;will&nbsp;execute&nbsp;the&nbsp;linq&nbsp;againbool&nbsp;hasAnyRecs&nbsp;=&nbsp;things.Any();//&nbsp;this&nbsp;will&nbsp;execute&nbsp;the&nbsp;linq&nbsp;statement&nbsp;*again*foreach(&nbsp;var&nbsp;thing&nbsp;in&nbsp;things&nbsp;)&nbsp;...//&nbsp;this&nbsp;will&nbsp;copy&nbsp;the&nbsp;results&nbsp;to&nbsp;a&nbsp;list&nbsp;in&nbsp;memoryvar&nbsp;list&nbsp;=&nbsp;things.ToList()//&nbsp;this&nbsp;won't&nbsp;iterate&nbsp;through&nbsp;again,&nbsp;the&nbsp;list&nbsp;knows&nbsp;how&nbsp;many&nbsp;items&nbsp;are&nbsp;in&nbsp;itint&nbsp;count2&nbsp;=&nbsp;list.Count();//&nbsp;this&nbsp;won't&nbsp;execute&nbsp;the&nbsp;linq&nbsp;statement&nbsp;-&nbsp;we&nbsp;have&nbsp;it&nbsp;copied&nbsp;to&nbsp;the&nbsp;listforeach(&nbsp;var&nbsp;thing&nbsp;in&nbsp;list&nbsp;)&nbsp;...
打开App,查看更多内容
随时随地看视频慕课网APP