MedicineMan
MedicineMan

Reputation: 15314

Linq expression throws an ArgumentNullException

GetSpecialNodes returns null sometimes. When it does, I get an ArgumentNullException thrown. Is there an elegant way of handling (a change to the linq expression) this besides calling GetSpecialNodes before running the Linq expression and doing a null check?

var nodes = (from HtmlNode node in document.GetSpecialNodes() select node);

Upvotes: 3

Views: 3913

Answers (3)

Razor
Razor

Reputation: 17498

If you have the option, change GetSpecialNodes() so it returns Enumerable.Empty<HtmlNode>() instead of null. It's always better to return an empty collection instead of null, then you can just check the collection for items using .Any() extension method.

Or as Stefan suggested:

var nodes = 
  from HtmlNode node in (document.GetSpecialNodes() ?? Enumerable.Empty<HtmlNode>())
  select node;

Upvotes: 0

Stefan
Stefan

Reputation: 14870

I guess you are doing more than just selecting the nodes coming from GetSpecialNodes(). Thus you probably want to avoid calling ToList() on GetSpecialNodes() to profit from deferred execution. You can use Enumerable.Empty<HtmlNode>() to create an empty set:

var nodes = document.GetSpecialNodes() ?? Enumerable.Empty<HtmlNode>();

I think your code will be more readable when you do this before defining the query:

var nodes = document.GetSpecialNodes() ?? Enumerable.Empty<HtmlNode>();
var result = from HtmlNode node in nodes where /* some predicate */

vs.

var nodes = (from HtmlNode node in (document.GetSpecialNodes() ?? Enumerable.Empty<HtmlNode>()) where /* some predicate */)

Upvotes: 3

Francois
Francois

Reputation: 10968

May be

var nodes = (document.GetSpecialNodes() ?? new List<HtmlNode>()).ToList<HtmlNode>()

Upvotes: 4

Related Questions