0

I have below code .ToDictionary is working unexpected and throwing an error "Object reference not found".

    var serviceOptions = serviceDurations.ToDictionary(so => so.OptionCode, StringComparer.OrdinalIgnoreCase);

var serviceLines = serivceLinePayments.Select(sl => new ServiceLine(serviceOptions[sl.option_code], Decimal.ToInt32(sl.quantity), sl.customer_paid_amount));

if i replace this code like.

var serviceOptions = serviceDurations.ToDictionary(so => so.OptionCode, StringComparer.OrdinalIgnoreCase);

//var serviceLines = serivceLinePayments.Select(sl => new ServiceLine(serviceOptions[sl.option_code], Decimal.ToInt32(sl.quantity), sl.customer_paid_amount));

List<ServiceLine> serviceLines = new List<ServiceLine>();
foreach (var item in serivceLinePayments)
{
var so = serviceOptions.FirstOrDefault(s => s.Value.OptionCode == item.option_code);
ServiceLine line = new ServiceLine( so.Value, Decimal.ToInt32(item.quantity), item.customer_paid_amount);
serviceLines.Add(line);
}

by using this code there is no exception but not able to figure out what is the real cause for this exception.

Prashant
  • 651
  • 2
  • 7
  • 25

1 Answers1

0

I believe your code line serviceDurations.ToDictionary( ... is throwing null reference exception and that's obvious cause serviceDurations instance is null for some reason and so the exception.

You will have to debug and find out why serviceDurations instance is null.

Rahul
  • 71,392
  • 13
  • 57
  • 105
  • Really? Then why does this exact same line work in the second snippet? – Gert Arnold May 29 '15 at 21:11
  • Really? Unreally? no idea but is there could be any other good reason for NRE? I may be missing ... you tell me. – Rahul May 29 '15 at 21:13
  • i think compiler handle lambda expression code in different way that we saw (debug step by step). in first line .ToDictionary(...) tries to create dictionary but 2nd line lamda expression comes into picture and tries to fetch value from dictionary object which is not yet created. – Prashant May 29 '15 at 21:18
  • Question is how do you handle the event where the data is empty? – Nicholas Feb 27 '19 at 22:49