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
know
but run some test and with 40,000 elements, with count it takes 00.0004618 while with the solution withMoveNext
only takes 00.0000067. With 2 elemnts3169
vs0011
and with 1 elements it's the same. As bigger the collection, count gets slower.