List
的边界已知,.Last()
是否枚举了集合?
我问这个是因为文档说它是由
Enumerable
定义的(在这种情况下,它会需要枚举集合)
如果它确实枚举了集合,那么我可以简单地通过索引访问最后一个元素(正如我们知道
.Count
的List<T>
),但必须这样做似乎很愚蠢......
不,它没有枚举它。它首先检查枚举是否可以转换为
IList<T>
(Array 和 List<T>
实现),然后将直接使用索引而不进行枚举。
Enumerable.Last
来源:
public static TSource Last<TSource>(this IEnumerable<TSource> source) {
if (source == null) throw Error.ArgumentNull("source");
IList<TSource> list = source as IList<TSource>;
if (list != null) {
int count = list.Count;
if (count > 0) return list[count - 1];
}
else {
using (IEnumerator<TSource> e = source.GetEnumerator()) {
if (e.MoveNext()) {
TSource result;
do {
result = e.Current;
} while (e.MoveNext());
return result;
}
}
}
throw Error.NoElements();
}