The extension method public static TSource Last<TSource>(this IEnumerable<TSource> source)for IEnumerable<TSource>uses optimization for the type source IList<TSource>, so that it does not iterate over the entire sequence when it can simply step to the end using indexing.
public static TSource Last<TSource>(this IEnumerable<TSource> source)
IEnumerable<TSource>
IList<TSource>
IList<TSource> tSources = source as IList<TSource>; if (tSources != null) { int count = tSources.Count; if (count > 0) { return tSources[count - 1]; } }
I slightly modified the code so that it was readable by mroe, but the functionality remained the same.
Why is it public static TSource Last<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)also not optimized when it can explicitly start the iteration from the end of the sequence?
public static TSource Last<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
If there should be something that matches the predicate, and it is near the beginning of the sequence, I still need to iterate to the very end. If at the end there is something suitable, I no longer need to sort out, because I started from the end.
, - .
IList<TSource> tSources = source as IList<TSource>; if (tSources != null) { int count = tSources.Count; if (count > 0) { for (int i = count - 1; i >= 0; i--) { if (predicate(tSources[i])) { return tSources[i]; } } } }
, , , : . , GetEnumerator() IEnumarble . , . , , , .
, IList<T> , - Last theList[theList.Count()-1] , ; , IList<T> . , , IList<T> , , , (, , , , ), , ( , , , 1 000 000 1000 , [- ], 1000 , ).
IList<T>
Last
theList[theList.Count()-1]
Last , . , (), ( ), , . , IList<T> , , "" , , unoptimized ", .
IList<T> / , , Last , , , , , , .