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....
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With