开发者

Linq fails instead of returning null?

开发者 https://www.devze.com 2022-12-15 19:26 出处:网络
I am trying 开发者_如何学JAVAto filter a list of items using the .Where method, and return the first item matching the filter.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消