Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if IEnumerable has a single element?

Tags:

c#

linq

Count() scans through all element, hence if (list.Count() == 1)will not perform well if enumerable contains a lot of elements.

Single() throws exception if there are not exactly one elements. Using try { list.Single(); } catch(InvalidOperationException e) {} is clumsy and inefficient.

SingleOrDefault() throws exception if there are more than one elements, hence if (list.SingleOrDefault() == null) (assuming TSource is of reference type) will not work for enumerables of size greater than one.

like image 200
Jatin Sanghvi Avatar asked Dec 15 '17 10:12

Jatin Sanghvi


1 Answers

var exactlyOne = sequence.Take(2).Count() == 1;

The Take extension method will not throw if there is less elements, it will simply return only those available.

like image 194
nvoigt Avatar answered Oct 23 '22 10:10

nvoigt