忽略linq查询中的空或空结果

时间:2018-09-11 19:50:07

标签: c# asp.net .net linq

我有以下linq查询,该查询应该返回一个称为 binders 的IEnumerable,该IEnumerable用于返回一个名为 ChemicalMixture 的对象:

public virtual ICollection<Element> EqualBinders { get; protected set; }


public Binder(Element first, Element second, Bindership b = null)
{
    Bindership = b ?? Bindership.EqualBinder;
    if(first !=null) FirstReference = new Reference(first.FullFormula);
    if(second !=null) SecondReference = new Reference(second.FullFormula);
}

var binders = chem.Where(e => e!= null).Select(
    e => new Binder(e, e.EqualBinders.SingleOrDefault(b => b !=null && b.Category.UseRole == InventoryRole.ICM)));
return new ChemicalMixture(baseChem, includes, binders);

起初我有

e.EqualBinders.Single()

但是那抛出了这个错误:

。单个错误:

  

System.InvalidOperationException:序列不包含匹配项   元素

经过大量阅读和研究,我认为将其更改为

  

e.EqualBinders.SingleOrDefault

将解决此问题,但这给了我这个新错误:

。SingleOrDefault错误:

  

System.NullReferenceException:对象引用未设置为实例   一个对象。

我认为,如果有时linq查询不返回任何内容,那么我只想不返回ChemicalMixture,而是继续处理linq查询,因为下一个查询可能返回一些内容。

那么我知道某些情况下linq查询的结果可能为null或什么都不是,该如何处理呢?

谢谢!

0 个答案:

没有答案
相关问题