Reputation: 679
I am trying to filter a list of items using the .Where method, and return the first item matching the filter.
However if there are no items matching the filter, instead of returning null it throws an exception.
Here is the line of code I am using:
DescendantNodes.Where(dNode => dNode.InnerText.Contains("rain")).First();
Is there a way to make this work except splitting to two instructions?
Thanks,
Teddy
Upvotes: 2
Views: 143
Reputation: 32629
You may also compress your statement thus:
DescendantNodes.FirstOrDefault(dNode => dNode.InnerText.Contains("rain"));
Upvotes: 7
Reputation: 21991
use FirstOrDefault()
DescendantNodes.Where(dNode => dNode.InnerText.Contains("rain"))
.FirstOrDefault();
Thanks
Upvotes: 4