Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Linq对象引用未设置为对象的实例-内部集合null_C#_Linq - Fatal编程技术网

C# Linq对象引用未设置为对象的实例-内部集合null

C# Linq对象引用未设置为对象的实例-内部集合null,c#,linq,C#,Linq,我遇到了导致异常的linq查询问题。我知道为什么会发生异常,但我不确定重写查询的最佳方法是什么。如果可能的话,我想把它保存在linq中,但如果这是更好的方法,我并不反对使用循环和空对象检测 这是我的查询-问题是,AnalysisResults有时为空(而不仅仅是一个空的实例化集合)。也就是说,前置集合也可能为null,因此我更喜欢一种可以应用于所有集合的方法 benchmarks = (from p in cacheData.SiteSources

我遇到了导致异常的
linq
查询问题。我知道为什么会发生异常,但我不确定重写查询的最佳方法是什么。如果可能的话,我想把它保存在
linq
中,但如果这是更好的方法,我并不反对使用循环和空对象检测

这是我的查询-问题是,
AnalysisResults
有时为空(而不仅仅是一个空的实例化集合)。也就是说,前置集合也可能为null,因此我更喜欢一种可以应用于所有集合的方法

benchmarks = (from p in cacheData.SiteSources
                              from q in p.SiteGroup.SiteGroupSites
                              from r in q.Site.AnalysisResults
                              where r.BufferTypeId == bufferTypeId &&
                              r.BufferValue == bufferValue
                              select r).ToList();

是否有一种简洁的方法来处理空
分析结果

是,使用
where
过滤那些
为空的情况:

benchmarks = (from p in cacheData.SiteSources
              from q in p.SiteGroup.SiteGroupSites
              where q.Site.AnalysisResults!=null
              from r in q.Site.AnalysisResults
              where r.BufferTypeId == bufferTypeId && r.BufferValue == bufferValue
              select r).ToList();

您可以添加一些
where
子句来检查null

benchmarks = (from p in cacheData.SiteSources
                          where p.SiteGroup.SiteGroupSites != null
                          from q in p.SiteGroup.SiteGroupSites
                          where q.Site.AnalysisResults != null
                          from r in q.Site.AnalysisResults
                          where r.BufferTypeId == bufferTypeId &&
                          r.BufferValue == bufferValue
                          select r).ToList();

将对象更改为不返回null,而是返回实际的空结果。这正是为什么在需要集合时不应返回null的原因。不过,混合使用这两种Linq语法有点麻烦。好吧,让我来修正一下,这是可行的-我以前从未在任何地方使用过
where
子句,只在底部使用过,很高兴看到在这种情况下它是如何工作的。