Reputation: 103
Do LastOrDefault() and Last() methods iterate each and every element of the list to find the last element? or Are they returning the value by searching based on the index of the element?
Upvotes: 1
Views: 894
Reputation: 56453
If it's a type IList
then no, it won't iterate each and every element as that would be very inefficient.
This is what they do:
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> e = source.GetEnumerator()) {
if (e.MoveNext()) {
TSource result;
do {
result = e.Current;
} while (e.MoveNext());
return result;
}
}
}
throw Error.NoElements();
}
and LastOrDefault
:
public static TSource LastOrDefault<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> e = source.GetEnumerator()) {
if (e.MoveNext()) {
TSource result;
do {
result = e.Current;
} while (e.MoveNext());
return result;
}
}
}
return default(TSource);
}
Note, as there are couple overloads of each method I've only shown one of each above, but if you're interested in the others then feel free to have a look at the source code:
Upvotes: 4