Linq fails instead of returning null?
I am trying 开发者_如何学JAVAto 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
You may also compress your statement thus:
DescendantNodes.FirstOrDefault(dNode => dNode.InnerText.Contains("rain"));
use FirstOrDefault()
DescendantNodes.Where(dNode => dNode.InnerText.Contains("rain"))
.FirstOrDefault();
Thanks
精彩评论