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...
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;
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