Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does List<T>.Last() enumerate the collection?

Considering the boundaries of a List are known, does .Last() enumerate the collection?

I ask this because the documentation says that it is defined by Enumerable (in which case it would need to enumerate the collection)

If it does enumerate the collection then I can simply access the last element by index (as we know the .Count of a List<T>) but it seems silly to have to do this....

like image 270
Matthew Avatar asked Jun 21 '12 16:06

Matthew


1 Answers

It does enumerate the collection if it's an IEnumerable<T> and not an IList<T>(with an Array or List the index would be used).

Enumerable.Last is implemented in the following way (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();
}
like image 107
Tim Schmelter Avatar answered Sep 18 '22 15:09

Tim Schmelter