Returning null if multiple instances are found

I have an IEnumerable and a predicate (Func) and I am writing a method that shall return a value if only one instance in the list matches the predicate. If the criteria is matched by none, then none was found. If the criteria is matched by many instances, then the predicate was insufficient to successfully identify the desired record. Both cases should return null.

What is the recommended way to express this in LINQ that does not result in multiple enumerations of the list?

The LINQ operator SingleOrDefault will throw an exception if multiple instances are found. The LINQ operator FirstOrDefault will return the first even when multiple was found.

MyList.Where(predicate).Skip(1).Any() 

...will check for ambiguity, but will not retain the desired record.

It seems that my best move is to grab the Enumerator from MyList.Where(predicate) and retain the first instance if accessing the next item fails, but it seems slightly verbose.

Am I missing something obvious?

Jon Skeet
people
quotationmark

The "slightly verbose" option seems reasonable to me, and can easily be isolated into a single extension method:

// TODO: Come up with a better name :)
public static T SingleOrDefaultOnMultiple<T>(this IEnumerable<T> source)
{
    // TODO: Validate source is non-null
    using (var iterator = source.GetEnumerator())
    {
        if (!iterator.MoveNext())
        {
            return default(T);
        }
        T first = iterator.Current;
        return iterator.MoveNext() ? default(T) : first;
    }
}

people

See more on this question at Stackoverflow