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

Mat*_*hew 10 .net c# collections linq-to-objects list

考虑到List已知的边界,是否.Last()列举了集合?

我问这个,因为文件说,这是定义Enumerable(在这种情况下,需要枚举集)

如果它枚举集合,然后我可以通过索引只需访问最后一个元素(如我们知道.CountList<T>),但它似乎愚蠢不得不这样做....

Tim*_*ter 11

它会枚举集合,如果它是一个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();
}
Run Code Online (Sandbox Code Playgroud)

  • @MatthewPK它是"是的,如果它不是一个`IList <T>`它会迭代整个可枚举的"有点令人困惑,但是正确的. (2认同)