Nikhil Agrawal Nikhil Agrawal - 3 months ago 13
C# Question

Do Enumerable.FirstOrDefault() stop when it finds item?

I tried searching on MSDN, SO and on Web but could not find answer.

Say I have a collection in which I do

FirstOrDefault()
. Let say it finds the item. Does its stop and returns the item or does it continue searching and hampers performance?

Answer

If you are still vague on this, the source code in .NET framework is implemented from here:

public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source) {
    if (source == null) throw Error.ArgumentNull("source");
    IList<TSource> list = source as IList<TSource>;
    if (list != null) {
        if (list.Count > 0) return list[0];
    }
    else {
        using (IEnumerator<TSource> e = source.GetEnumerator()) {
            if (e.MoveNext()) return e.Current;
        }
    }
    return default(TSource);
}

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

Apparently, it will stop if founded