【发布时间】:2021-09-20 05:15:57
【问题描述】:
我相信这个问题的答案在这里得到了很好的解释:LINQ Ring: Any() vs Contains() for Huge Collections
但我的问题是针对当前实现的
IEnumerable<T> msgs = null;
/// ...
/// some method calls which returns a long list of messages
/// The return type of the method is IEnumerable<T>
/// List<T> ret = new List<T>();
/// ...
/// return ret
/// ...
if (msgs.Any())
object= msgs.Last();
msgs 是一个在内存中的集合(IEnumerable)表示。 Any() 在这里如何工作?这个 Any() 方法调用没有条件,不就是 O(1) 吗?还是它仍然查看每个元素?
【问题讨论】:
-
如果
IEnumerable是ICollection,它会查看计数,如果不是,它将调用IEnumeratorMoveNext并返回结果。这里没有魔法 -
这里的底层类型是什么?除非您提供具体信息,否则我们无法提供任何具体信息。是
List<T>还是更复杂的数据库查询? -
The msgs is an in memory collection (IEnumerable) said具体类型是什么?请分享minimal reproducible example。 -
@TheGeneral
Any从不查看Count属性。 github.com/microsoft/referencesource/blob/master/System.Core/…Count()扩展方法尝试并查找ICollection<T>.Count和ICollection.Count,但不是 Any()。 -
如果您执行
Console.WriteLine(msgs.GetType()),您会在控制台中看到什么打印?