GetSpecialNodes有时会返回null。当它发生时,我得到抛出的ArgumentNullException。除了在运行Linq表达式和执行空检查之前调用GetSpecialNodes之外,是否还有一种优雅的处理方式(对linq表达式的更改)?Linq表达式抛出ArgumentNullException
var nodes = (from HtmlNode node in document.GetSpecialNodes() select node);
GetSpecialNodes有时会返回null。当它发生时,我得到抛出的ArgumentNullException。除了在运行Linq表达式和执行空检查之前调用GetSpecialNodes之外,是否还有一种优雅的处理方式(对linq表达式的更改)?Linq表达式抛出ArgumentNullException
var nodes = (from HtmlNode node in document.GetSpecialNodes() select node);
可能
var nodes = (document.GetSpecialNodes() ?? new List<HtmlNode>()).ToList<HtmlNode>()
我猜你正在做的不仅仅是选择从GetSpecialNodes()
到来的节点更多。因此,您可能希望避免在GetSpecialNodes()
上拨打ToList()
从延期执行中获利。您可以使用Enumerable.Empty<HtmlNode>()
创建一个空集:
var nodes = document.GetSpecialNodes() ?? Enumerable.Empty<HtmlNode>();
我认为当你定义查询之前做到这一点你的代码将更具可读性:
var nodes = document.GetSpecialNodes() ?? Enumerable.Empty<HtmlNode>();
var result = from HtmlNode node in nodes where /* some predicate */
与
var nodes = (from HtmlNode node in (document.GetSpecialNodes() ?? Enumerable.Empty<HtmlNode>()) where /* some predicate */)
如果您有选择,请更改GetSpecialNodes()
,以便它返回Enumerable.Empty<HtmlNode>()
而不是null
。最好是返回一个空集合而不是null,然后您可以使用.Any()
扩展方法检查集合中的项目。
或者像斯特凡建议:
var nodes =
from HtmlNode node in (document.GetSpecialNodes() ?? Enumerable.Empty<HtmlNode>())
select node;
已'document'值还是空? – Fischermaen 2012-01-02 08:28:25