Optimization in the SingleOrDefault Linq Function

Here is the code extracted from the SingleOrDefault function:

public static TSource SingleOrDefault<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);
    long count = 0; 
    foreach (TSource element in source) {
        if (predicate(element)) { 
            result = element; 
            checked { count++; }
        } 
    }
    switch (count) {
        case 0: return default(TSource);
        case 1: return result; 
    }
    throw Error.MoreThanOneMatch(); 
} 

I am interested to know if there is a reason that after finding more than one element in the loop there is no break statement to prevent the rest of the list from being transcoded. In any case, an error will occur. For a large list where more than one item is found at the beginning, I think that would make a huge difference.

+5
source share
1 answer

Jon Skeet found this by redefining LINQ for objects as part of his EduLinq blog series :

, LINQ to Objects throw InvalidOperationException, , , , . - Connect ; , .

Connect , , Microsft :

, Single, - , , , .

, , , Single , . " ", , Visual Studio. , , .

2011 ...

+7

All Articles