开发者

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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜