I have a List<>
with N items. I want to get the first element if and only if N = 1. Can this be done using lambda
or some other nice construct?
This works, but looks horrible:
var blah = new List<Object>() { new Object() };
var item = (blah.Count == 1 ? blah[0] : null);
There are several LINQ extension methods.
SingleOrDefault
If there is one element it will be returned, if there are none default<T>
will be returned, if there are multiple an exception is thrownFirstOrDefault
If there is one element it will be returned, if there are none default<T>
will be returnedElementAtOrDefault
returns the element at the given position or default<T>
if the sequence has not so many elementsSo for example (my preferred for your requirement):
var item = blah.ElementAtOrDefault(0);
The best method for your requirement depends on how strict this rule is:
I want to get the first element if and only if N = 1.
If it's exceptional that there is more than one element in the sequence, use SingleOrDefault
and you'll be informed (error-log) if it gets out of hand.
If it's important that you get the first element and you'll never want another element, use better FirstOrDefault
because it has a meaningful name.
If the index of the element in the sequence is important and you (currently) need the first element, but that might change in future, use ElementAtOrDefault
.
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