List<T>.Last()是否枚举集合?

问题描述 投票:0回答:1

考虑到

List
的边界已知,
.Last()
是否枚举了集合?

我问这个是因为文档说它是由

Enumerable
定义的(在这种情况下,它需要枚举集合)

如果它确实枚举了集合,那么我可以简单地通过索引访问最后一个元素(正如我们知道

.Count
List<T>
),但必须这样做似乎很愚蠢......

c# .net list collections linq-to-objects
1个回答
12
投票

不,它没有枚举它。它首先检查枚举是否可以转换为

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();
}
© www.soinside.com 2019 - 2024. All rights reserved.