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?
Best Answer
You can use
IEnumerable.First()
orIEnumerable.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 returndefault(T)
(null
if it's a reference type).