How can I find if my list contains one and only one item without Count
or Single
?
Possible dupe of Efficient Linq Enumerable's 'Count() == 1' test
How can I find if my list contains one and only one item without Count
or Single
?
Possible dupe of Efficient Linq Enumerable's 'Count() == 1' test
How about this:
int limitedCount = myEnumerable.Take(2).Count();
That will give you:
... but it gives you those answers whilst only iterating over the sequence once. You can then switch on the results.
rather than use the exception, loop through the enumerable and as soon as you hit more than 1, break out of it.
You don't have to count them all...just 2 of them :)
Also, using exceptions for flow-control is a bad idea because its really expensive from a performance standpoint.
As @Jon Skeet's answer shows, there are better ways to do this since the IEnumerable interface is so well designed. If it didn't have the .Skip
and .Any()
methods, however (which would apply to other languages or places where you are only simply iterating), you only need to count to 2.