考虑 List
的边界是已知的,确实.Last()
枚举集合?
我问这个是因为 documentation说它是由 Enumerable
定义的(在这种情况下,它将需要枚举集合)
如果它确实枚举了集合,那么我可以简单地通过索引访问最后一个元素(正如我们所知的 .Count
的 List<T>
),但必须这样做似乎很愚蠢。 ...
最佳答案
如果集合是 IEnumerable<T>
,它会枚举集合而不是 IList<T>
(对于数组或列表,将使用索引)。
Enumerable.Last
通过以下方式实现(ILSpy):
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> enumerator = source.GetEnumerator())
{
if (enumerator.MoveNext())
{
TSource current;
do
{
current = enumerator.Current;
}
while (enumerator.MoveNext());
return current;
}
}
}
throw Error.NoElements();
}
关于c# - List<T>.Last() 是否枚举集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11143042/