0

When I Using C# linq expression with contains , I got an Error like "Object reference not set to an instance of an object". My Code Segement is,

var query = GetUserDataForList();// It contains the data I want
 search = (search == null) ? "" : search;
 string searchText = (search == null) ? "" : search.ToLower().ToString();

 var users = query.Where(a => a.Email.ToLower().Contains(searchText) && a.Email != null).AsEnumerable();
 users = users.Skip(rowsPerPage * (page - 1)).Take(rowsPerPage).AsEnumerable();

any idea how to solve that?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364

1 Answers1

4

Your conditions in Where clause should be like:

a.Email != null && a.Email.ToLower().Contains(searchText)

Because only then it will short-circuit in case of null. Right now even if your Email is null it will try to use use ToLower and give you NRE.

See: && Operator (C# Reference)

The conditional-AND operator (&&) performs a logical-AND of its bool operands, but only evaluates its second operand if necessary

Habib
  • 219,104
  • 29
  • 407
  • 436