I have the follow linq query that is supposed to return an IEnumerable called binders, which is used to return an object called 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);
At first I had
e.EqualBinders.Single()
but that was throwing this error:
.Single error:
System.InvalidOperationException: Sequence contains no matching element
After a lot of reading and some research, I thought changing it to
e.EqualBinders.SingleOrDefault
would fix the issue, but that gives me this new error:
.SingleOrDefault error:
System.NullReferenceException: Object reference not set to an instance of an object.
I think, if sometimes the linq query doesn't return anything, then I'd just like to not return a ChemicalMixture, but keep on processing the linq query because the next one might return something.
So how can I handle this, knowing sometimes the result of the linq query might be null or nothing?
Thanks!