Linq SelectMany.Distinct.ToList()

use*_*219 0 c# linq

我正在寻找与此错误的一些输入。我对一些事情很清楚,但不确定如何解决此linq表达式。我们的用户会发生此错误,我无法重现此问题。因此,我试图找到在selectmany中使用不同运算符的位置,并在例程中发现了一个实例。

  var finishedReqs = allDocs.SelectMany(x => x.Reqs).Distinct().ToList();
  var finishedReqsWithDocs = finishedReqs.Where(x => x.Docs.Any());
  if (finishedReqsWithDocs.Any())
     {
     //Call another routine
     }
Exception
-----------------
Message:
Object reference not set to an instance of an object.

Stack Trace:
   at System.Linq.Enumerable.<SelectManyIterator>d__14`2.MoveNext()
   at System.Linq.Enumerable.<SelectManyIterator>d__14`2.MoveNext()
   at System.Linq.Enumerable.<DistinctIterator>d__81`1.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
Run Code Online (Sandbox Code Playgroud)

我了解如果集合为null,SelectMany将返回null而不是一个空列表。然后我很困惑,因为我们做了一个Distinct.ToList()。我需要在哪里检查空值。Resharper告诉我Distinct.ToList()的第一个表达式永远不能为null

if(finishedReqs!=null) //Resharper has squiggly lines with expression is always true
{
}
Run Code Online (Sandbox Code Playgroud)

Sco*_*ain 5

它不是不finishedReqs为null,它是其中为null的条目之一allDocs

如果查看堆栈跟踪,最顶层是

在System.Linq.Enumerable.d__14`2.MoveNext()

这意味着它在内部失败Enumerable.SelectManyIteratorallDocs它中的某个位置持有一个空Document对象。

如果错误是x.Reqsnull,则异常的顶层将位于代码中的匿名lambda表达式内。

解决该问题的方法是在执行以下操作之前排除所有空文档 SelectMany

allDocs.Where(x=> x != null).SelectMany(x => x.Reqs).Distinct().ToList();
Run Code Online (Sandbox Code Playgroud)