Using LINQ what is the best way to select a single item from a list if the item may not exists in the list?
I have come up with two solutions, neither of which I like. I use a where clause to select the list of items (which I know will only be one), I can then check the count and make a Single call on this list if count is one, the other choice is to use a foreach and just break after getting the item.
Neither of these seem like a good approach, is there a better way?
You can use IEnumerable. First() or IEnumerable. FirstOrDefault() . The difference is that First() will throw if no element is found (or if no element matches the conditions, if you use the conditions).
You can use IEnumerable.First()
or IEnumerable.FirstOrDefault()
.
The difference is that First()
will throw if no element is found (or if no element matches the conditions, if you use the conditions). FirstOrDefault()
will return default(T)
(null
if it's a reference type).
Use the FirstOrDefault selector.
var list = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var firstEven = list.FirstOrDefault(n => n % 2 == 0); if (firstEven == 0) Console.WriteLine("no even number"); else Console.WriteLine("first even number is {0}", firstEven);
Just pass in a predicate to the First or FirstOrDefault method and it'll happily go round' the list and picks the first match for you.
If there isn't a match, FirstOrDefault will returns the default value of whatever datatype the list items is.
Hope this helps :-)
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