c# - Where function on list with multiple conditions returns errors -
i'm trying filter list based on few criteria , .where() function gives me error in 2 parts of same method.
if (string.isnullorwhitespace(champs))             {                 data = dal.getvuetache().where(t =>                     t.projetdescription64.tolower().contains(filtre.tolower())                      // *this line || t.projetdescription256.tolower().contains(filtre.tolower())                     || t.description256.tolower().contains(filtre.tolower())                     ||t.responsablenomcourt.tolower().contains(filtre.tolower())                     || t.prioritedesc.tolower().contains(filtre.tolower())                     ).tolist();             }   if use of previous conditions except 1 on nullable field alone filtered list on criteria, if add or "||" system.nullreferenceexception on first criteria.
i have similar issue in part of same method
else                 {                        data = dal.getvuetache().where(t =>                          t.gettype().getproperty(champs).getvalue(t).tostring().tolower().contains(filtre.tolower())                         ).tolist();                 }   this 1 filters list based on criteria "filtre" on property "champs". works on every property second one, nullable one. understand issue comes from, can't find way test if property null before evaluating , work around inside .where() method.
any advice appreciated!!
edit :
thanks ivan stoev solution!
the correct syntax testing null value in first case is:
|| (t.projetdescription256 != null && t.projetdescription256.tolower().contains(filtre.tolower()))   in second case:
(t.gettype().getproperty(champs).getvalue(t) != null && t.gettype().getproperty(champs).getvalue(t).tostring().tolower().contains(filtre.tolower()))      
just null check either old way:
|| (t.projetdescription256 != null && t.projetdescription256.tolower().contains(filtre.tolower()))   or c# 6 way (utilizing null conditional operator):
|| t.projetdescription256?.tolower().contains(filtre.tolower()) == true   btw, can simplify similar checks , avoid such errors writing simple custom extension methods this:
public static class stringextensions {     public static bool containsignorecase(this string source, string target)     {         return source == null ? target == null : target != null && source.indexof(target, stringcomparison.currentcultureignorecase) >= 0;     } }   so snippet becomes simply:
data = dal.getvuetache().where(     t => t.projetdescription64.containsignorecase(filtre)      || t.projetdescription256.containsignorecase(filtre)     || t.description256.containsignorecase(filtre)     || t.responsablenomcourt.containsignorecase(filtre)     || t.prioritedesc.containsignorecase(filtre) ).tolist();      
Comments
Post a Comment