为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

守着一只汪 2019-06-29 14:42:49
我数字与列表-使用什么?它们是如何工作的?我对枚举器的工作方式和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,当我调试和检查“sel”(在这种情况下是IEnDigable)时,它有一些有趣的成员:“innerKeySelector”、“innerKeySelector”和“outerKeySelector”,最后两个成员似乎是委托。“内部”成员没有“动物”实例,而是“物种”实例,这对我来说很奇怪。“外部”成员确实包含“动物”实例。我想是由两位代表来决定哪些是进去的,哪些是从里面出来的?我注意到,如果使用“DISTISTION”,“Inside”包含6项(这是不正确的,因为只有2项是不同的),但是“外部”确实包含正确的值。同样,可能是委托方法决定了这一点,但这比我对IEnDigable的了解要多一点。最重要的是,这两种选择中哪一种表现最好?通过.ToList()?或者直接使用枚举器?如果可以的话,也请解释一下或抛出一些链接来解释IEnDigable的这种用法。
查看完整描述

2 回答

?
POPMUISE

TA贡献1765条经验 获得超5个赞

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


查看完整回答
反对 回复 2019-06-29
?
不负相思意

TA贡献1777条经验 获得超10个赞

实现的类IEnumerable允许您使用foreach语法。

基本上,它有一个方法来获取集合中的下一个项。它不需要整个集合在内存中,也不知道其中有多少项,foreach一直拿到下一件直到用完为止。

在某些情况下,这可能非常有用,例如,在大规模数据库表中,在开始处理行之前,您不希望将整个事件复制到内存中。

现在List实施器IEnumerable,但表示内存中的整个集合。如果你有IEnumerable然后你打电话.ToList()创建一个新列表,其中包含内存中枚举的内容。

Linq表达式返回枚举,默认情况下,当您使用foreach..阿IEnumerable循环时执行Linq语句。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 ) ...


查看完整回答
反对 回复 2019-06-29
  • 2 回答
  • 0 关注
  • 391 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信