在foreach语句中执行LINQ是否更有效?
这些陈述有同样的事情吗?
var listA = someList.TakeWhile(predicate);
foreach(var item in listA)
{
/// perform code here
}
versus ...
foreach(var item in someList.TakeWhile(predicate))
{
/// perform some code here
}
集合是先创建的,然后通过O(n^2)迭代?还是该集合迭代为其创建O(n)?
Do these statements do the same exact thing?
var listA = someList.TakeWhile(predicate);
foreach(var item in listA)
{
/// perform code here
}
versus...
foreach(var item in someList.TakeWhile(predicate))
{
/// perform some code here
}
Is the collection created first and then iterated through O(N^2)? Or is the collection iterated through as its being created O(N)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
@Jeremy Lakeman在评论中提供了正确的答案。
变量
lista
的类型在:is
iEnumerable< t>
,t是您集合的单个元素somelist
的单个元素的类型。take take
方法的签名清楚地表明了这一点:如
take take take
文档页面。声明类型
iEnumerable< t>
的变量不会枚举它。要列举
iEnumerable
,您必须明确地进行,如果 foreach 循环,或者使用它来产生新的实体集合,例如list
,字典
等... ...在(例如)
tolist
文档:因此,在您的两个代码示例中,
iEnumerable
您构建的将在循环中仅列举一次。另外:即使您在列举之前已经实现了收集:
它仍然是O(n)操作,而不是O(n^2)。
如果您从
somelist
集合中获取n个元素,则将用.tolist()
呼叫一次枚举它们,然后在foreach
loop中,总共2 x n,而不是n^2。@Jeremy Lakeman provided the right answer in comments.
The type of the variable
listA
in:is
IEnumerable<T>
, T being the type of an individual element of your collectionsomeList
. This is clearly shown by the signature of theTakeWhile
method:as can be seen at the
TakeWhile
documentation page.Declaring a variable of type
IEnumerable<T>
doesn't enumerate it.To enumerate an
IEnumerable
, you have to do it explicitly, by enumerating it if aforeach
loop for instance, or by using it to produce a new materialized collection, such as aList
,Dictionary
, etc... by calling methods such.ToList()
orToDictionary()
, etc...This is explicitly stated in the (for instance)
ToList
documentation:So in both your code examples, the
IEnumerable
you construct will be enumerated only once in theforeach
loop.Also: even if you had materialized your collection before enumerating it:
It would still be an O(n) operation, not an O(n^2).
If you take N elements from your
someList
collection, you will enumerate them once with the.ToList()
call, and once in theforeach
loop, for a total of 2 x N, not N^2.两种形式都是相同的。根据Microsoft文档,查询(
take the
)直到其getEnumerator
方法直接或foreach调用。Both forms are same. According to Microsoft documentation the query (
TakeWhile
) won't execute until itsGetEnumerator
method is called directly or by foreach.source