Question : Does SingleOrDefault return null on multiple results?

SingleOrDefault() is supposed to return an exception if there is more than one result returned: http://msdn.microsoft.com/en-us/library/bb342451.aspx.  I took the sql this method is sending to SQL Server and ran it in a query window.  I got back two results.  The method is returning null without throwing an exception.

Any ideas why the discrepancy?

Answer : Does SingleOrDefault return null on multiple results?

This is from Reflector:

public static TSource SingleOrDefault(this IEnumerable source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    IList list = source as IList;
    if (list != null)
    {
        switch (list.Count)
        {
            case 0:
                return default(TSource);

            case 1:
                return list[0];
        }
    }
    else
    {
        using (IEnumerator enumerator = source.GetEnumerator())
        {
            if (!enumerator.MoveNext())
            {
                return default(TSource);
            }
            TSource current = enumerator.Current;
            if (!enumerator.MoveNext())
            {
                return current;
            }
        }
    }
    throw Error.MoreThanOneElement();
}

It should throw exception if there're more than one element.
Random Solutions  
 
programming4us programming4us