C# – There’s a most performant way to check that a collection has exactly 1 element

clinq

I came up with this solution :

if (Take(2).Count() == 1)

is there any more performance solution (or better syntactical sugar) to do this check ?
I want a performance way because this will be an extension used on Linq To Entites and Linq to Objects.

I'm not using SingleOrDefault because that will throw and exception if it has more than 1 element.

Based on @Telastyn answer I came up with the following:

public static bool HasOne<T>(this IEnumerable<T> enumerable) {
    var enumerator = enumerable.GetEnumerator();
    return enumerator.MoveNext() && !enumerator.MoveNext();
}

another implementation (slighly slower but 100% sure will work effectivly on Linq to Entities) would be :

public static bool HasOne<T>(this IEnumerable<T> enumerable) {
    return !enumerable.FirstOrDefault().Equals(default(T)) && !enumerable.Skip(1).Any();
}

I'm not sure if the MoveNext one works with IQueryable on Linq to Entites. (any takers? I don't know how to test that)

After some test, Take(2).Count() == 1; is the fastest. :S

Best Answer

Yes, making your own extension that returns false on the second successful MoveNext (or none) should be the most performant implementation for IEnumerable. Anything with a Count property should just check if it is equal to one.