Test if an IEnumerable<T> contains 1 element without counting or using Single
How can I find if my list contains one and only one item without Count
or Single
?
Possible dupe of Efficient Linq Enumerable开发者_如何学JAVA39;s 'Count() == 1' test
How about this:
int limitedCount = myEnumerable.Take(2).Count();
That will give you:
- 0 if it was empty
- 1 if it had exactly 1 element
- 2 if it had 2 or more elements
... but it gives you those answers whilst only iterating over the sequence once. You can then switch on the results.
myEnumerable.Take(2).Count() < 2
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.
精彩评论