Reputation: 15314
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
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
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
Reputation: 10968
May be
var nodes = (document.GetSpecialNodes() ?? new List<HtmlNode>()).ToList<HtmlNode>()
Upvotes: 4