Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if an IEnumerable<T> contains 1 element without counting or using Single

Tags:

.net

linq

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

like image 720
Ray Avatar asked Sep 16 '11 16:09

Ray


2 Answers

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.

like image 70
Jon Skeet Avatar answered Nov 20 '22 05:11

Jon Skeet


myEnumerable.Take(2).Count() < 2
like image 38
Muhammad Hasan Khan Avatar answered Nov 20 '22 03:11

Muhammad Hasan Khan