Linq表达式抛出ArgumentNullException

时间:2012-01-02 08:26:00

标签: c# linq

GetSpecialNodes有时会返回null。如果是这样,我会抛出一个ArgumentNullException。除了在运行Linq表达式并进行空检查之前调用GetSpecialNodes之外,还有一种优雅的处理方式(更改linq表达式)吗?

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

3 个答案:

答案 0 :(得分:3)

可能是

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

答案 1 :(得分:2)

我猜你所做的不仅仅是选择来自GetSpecialNodes()的节点。因此,您可能希望避免在ToList()上调用GetSpecialNodes()以从延迟执行中获利。您可以使用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 */

VS

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

答案 2 :(得分:0)

如果您有选项,请更改GetSpecialNodes(),使其返回Enumerable.Empty<HtmlNode>()而不是null。返回空集合而不是null总是更好,然后您可以使用.Any()扩展方法检查项目集合。

或者斯特凡建议:

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