我遇到了导致异常的 linq 查询问题。我知道为什么会发生异常,但我不确定重写查询的最佳方法是什么。如果可能的话,我想将它保留在 linq 中,但如果这是更好的方法,我不反对使用循环和空对象检测。
这是我的查询 - 问题是 AnalysisResults 有时为空(不仅仅是一个空的实例化集合)。也就是说,前身集合也有可能为空,因此我更喜欢一种可以应用于所有集合的方法。
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();
是否有一种简洁的方法来解决 null AnalysisResults?
请您参考如下方法:
是的,使用 Where 过滤那些 null 的情况:
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();
