Wesly
Wesly

Reputation: 679

Linq fails instead of returning null?

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

Answers (2)

Aviad P.
Aviad P.

Reputation: 32629

You may also compress your statement thus:

DescendantNodes.FirstOrDefault(dNode => dNode.InnerText.Contains("rain"));

Upvotes: 7

Mahesh Velaga
Mahesh Velaga

Reputation: 21991

use FirstOrDefault()

DescendantNodes.Where(dNode => dNode.InnerText.Contains("rain"))
                                              .FirstOrDefault();

Thanks

Upvotes: 4

Related Questions