I want to check that an IEnumerable contains exactly one element. This snippet does work:
bool hasOneElement = seq.Count() == 1
However it’s not very efficient, as Count() will enumerate the entire list. Obviously, knowing a list is empty or contains more than 1 element means it’s not empty. Is there an extension method that has this short-circuiting behaviour?
This should do it:
You could elide this further, but I don’t suggest you do so:
It’s the sort of trick which is funky, but probably shouldn’t be used in production code. It’s just not clear enough. The fact that the side-effect in the LHS of the && operator is required for the RHS to work appropriately is just nasty… while a lot of fun 😉
EDIT: I’ve just seen that you came up with exactly the same thing but for an arbitrary length. Your final return statement is wrong though – it should be return
!en.MoveNext(). Here’s a complete method with a nicer name (IMO), argument checking and optimization forICollection/ICollection<T>:EDIT: And now for functional fans, a recursive form of
CountEquals(please don’t use this, it’s only here for giggles):EDIT: Note that for something like LINQ to SQL, you should use the simple
Count()approach – because that’ll allow it to be done at the database instead of after fetching actual results.