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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With