microsoft / referencesource

Source from the Microsoft .NET Reference Source that represent a subset of the .NET Framework
https://referencesource.microsoft.com/
MIT License
3.16k stars 1.27k forks source link

Question for Linq Last #77

Closed omansak closed 5 years ago

omansak commented 5 years ago

Can anyone explain this code?

public static TSource Last<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) {
            if (source == null) throw Error.ArgumentNull("source");
            if (predicate == null) throw Error.ArgumentNull("predicate");
            TSource result = default(TSource);
            bool found = false;
            foreach (TSource element in source) {
                if (predicate(element)) {
                    result = element;
                    found = true;
                }
            }
            if (found) return result;
            throw Error.NoMatch();
        }

Why not ise this

foreach (TSource element in source) {
                if (predicate(element)) {
                    return  element;
                }
            }

Why create extra variable for result ? Why more iteration after found?

0xfeeddeadbeef commented 5 years ago

Because several elements might match the predicate, and we want only last one.

(By the way, this repository is not the right place to ask questions).