Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Get single result or null

Tags:

c#

linq

is there any LINQ function that returns only 1 element when the list has 1 element and if the list is empty or has more than 1 element it return's null? The SingleOrDefault throws an exception when the list have more than 1 element...

like image 217
Luís Tiago Avatar asked Jan 25 '26 13:01

Luís Tiago


1 Answers

You can write this method by yourself

var list = new List<object>();
var result = list.Count() == 1 ? list.FirstOrDefault() : null;

More performant option with taking only first two elements in a collection (as @canton7 mentioned in comments)

var result = list.Take(2).Count() == 1 ? list.FirstOrDefault() : null;

Also, Single can be used instead of FirstOrDefault, but both methods do the same, cast source sequence to IList and get the first element.

Since, per question, the source collection is List<T>, it'll make sense to use List<T> indexer and Count property

var result = list.Count == 1 ? list[0] : null;
like image 146
Pavel Anikhouski Avatar answered Jan 27 '26 03:01

Pavel Anikhouski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!