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

标签 c# .net list collections linq-to-objects

考虑 List 的边界是已知的,确实.Last()枚举集合?

我问这个是因为 documentation说它是由 Enumerable 定义的(在这种情况下,它需要枚举集合)

如果它确实枚举了集合,那么我可以简单地通过索引访问最后一个元素(正如我们所知的 .CountList<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/

相关文章:

c# - Xamarin.Forms 设置 IsVisible 在函数完成之前不会触发。

c# - 在 C# 中高效地复制对称矩阵

c# - XAML-如何动态设置 ScrollViewer 的大小?

c# - 在 MDI 容器中将每个子窗体作为单独的线程运行

c# - 如何使用双 (.) (.) "fileName ..pdf"验证安全文件名

.net - .net在IComparer中使用了哪种排序算法

c# - 将标量从 SQL Server 返回到 C#

r - 根据行号将值分配给列表中各个数据帧的行

python - 使用列表项作为嵌套字典的键

java - 在java中将map的map转换为map的列表