0

in my code there is a ddlitemid that can be null and in Linq query my code is like

valuecheck = _allQuestions.Where(x => x.nID == ddlItemId).FirstOrDefault().strName;

if ddlitemid not exist in my database it gives error i wants to handle null reference object error

raja atif
  • 188
  • 1
  • 13
  • You should probably look at this question/answer here first: http://stackoverflow.com/questions/15948369/how-to-handle-null-values-in-linq - I think that's what you are looking for? – joshmcode Mar 19 '15 at 18:21
  • hi i saw that earlier my pattern is different than that question so that's why i ask question ok – raja atif Mar 20 '15 at 06:24

3 Answers3

2

Then separate the call to FirstOrDefault from the access of strName. Also you can remove the Where and put the lambda filter into the FirstOrDefault.

var quesiton = _allQuestions.FirstOrDefault(x => x.nID == ddlItemId);
if(question != null)
{
    valuecheck = question.strName;
}
juharr
  • 31,741
  • 4
  • 58
  • 93
2

I see this pattern FirstOrDefault().SomeProperty very often. It has two drawbbacks.

  1. You always need to do a null check on FirstOrDefault().
  2. It is not efficient.

About the second point: FirstOrDefault() grabs a whole entity from the database and you use only one field from it. You can kill two birds with one stone by doing:

valuecheck = _allQuestions.Where(x => x.nID == ddlItemId)
                          .Select(q => q.strName)
                          .FirstOrDefault();

Or .FirstOrDefault() ?? string.Empty.

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
1

The way I normally handle this is to assign my linq results to a variable and then check for null.

var tempStorage = _allQuestions.Where(x => x.nID == ddlItemId).FirstOrDefault();

if(tempStorage != null)
{
    valuecheck = tempStorage.strName;
}

This way you don't have to worry about the null ref exception since you check the existence first.