0

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!

SkyeBoniwell
  • 5,272
  • 8
  • 62
  • 128
  • 1
    before you do your select, do your null check ie: chem.Where(e => e != null).Select(...) – Chris Bartlett Sep 11 '18 at 20:29
  • 1
    Follow the stack trace, it probably leads you to this line in the constructor: `SecondReference = new Reference(second.FullFormula);`. So `second` can be null but you don't check for it and call `second.FullFormula`, hence the NRE. I do recommend you read through the duplicate, it will illustrate how you can debug this on your own which should save you time the next time it happens (and it will happen again, NRE is the most frequently occurring exception). – Igor Sep 11 '18 at 20:42
  • @Igor thanks for your suggestions! I appreciate it. I did run through the debugger multiple times, setting breakpoints along the way. But Visual Studio wouldn't let me set breakpoints inside the Linq query, so it was hard(for me at least) to see exactly what was going on. – SkyeBoniwell Sep 12 '18 at 14:10
  • @Igor I added a few checks for null. Please see edited question. However, I am still getting the Exceptions. :( – SkyeBoniwell Sep 12 '18 at 15:12
  • It would help if you posted the stack trace from the exception into your question. – Igor Sep 12 '18 at 15:13

0 Answers0