3

I have to find a word in a LINQ to EF search. so I wrote the following code

 var Q = (from k in MyList 
                 where k.Name.Contains(query) || k.Description.Contains(query)   
                   select k).Count();
 if (Q == 0)
      continue;

But The 'Description' field can be null sometimes. And I get error in those cases. Is there any way that I can avoid the error ??

Reza.Hoque
  • 2,690
  • 10
  • 49
  • 78

1 Answers1

5

Check for null before doing Contains:

var Q = (from k in MyList 
             where k.Description!=null && (k.Name.Contains(query) || k.Description.Contains(query))   
               select k).Count();
if (Q == 0)
  continue;

Or possibly better:

var Q = (from k in MyList 
             k.Name.Contains(query)  || 
              ( string.IsNullOrEmpty(k.Description)? false :   
                k.Description.Contains(query))   
               select k).Count();
if (Q == 0)
  continue;
Icarus
  • 63,293
  • 14
  • 100
  • 115