tags:

views:

302

answers:

3

How is the method SingleOrDefault() evaluated in LINQ? Does it use a Binary Search behind the scenes?

A: 

I don't think it does any searching, it's all about getting the first element of the source [list, result set, etc].

My best guess is that it just pulls the first element. If there is no first it returns the default (null, 0, false, etc). If there is a first, it attempts to pull the second result. If there is a second result it throws an exception. Otherwise it returns the first result.

AgileJon
+2  A: 

I would assume that it simply performs the query and if the result count is zero, it returns the default instance of the class. If the result count is one, it returns that instance, and if the result count is greater than one, it throws an exception.

tvanfosson
+10  A: 

Better than attempting to explain in words, I thought I'd just post the exact code of implementation in the .NET Framework, retrieved using the Reflector program (and reformatted ever so slightly).

public static TSource SingleOrDefault<TSource>(this IEnumerable<TSource> source)
{
    if (source == null)
        throw Error.ArgumentNull("source");

    IList<TSource> list = source as IList<TSource>;
    if (list != null)
    {
        switch (list.Count)
        {
            case 0:
                return default(TSource);
            case 1:
                return list[0];
        }
    }
    else
    {
        using (IEnumerator<TSource> enumerator = source.GetEnumerator())
        {
            if (!enumerator.MoveNext())
                return default(TSource);

            TSource current = enumerator.Current;
            if (!enumerator.MoveNext())
                return current;
        }
    }

    throw Error.MoreThanOneElement();
}

It's quite interesting to oberserve that an optimisation is made if the object is of type IList<T>, which seems quite sensible. It simply falls back to enumerating over the object otherwise if the object implements nothing more specific than IEnumerable<T>, and does so just how you'd expect.

Note that it can't use a binary search because the object doesn't necessarily represent a sorted collection. (In fact, in almost all usage cases, it won't.)

Noldorin