Piotr P Piotr P - 3 months ago 10
C# Question

If null then set it to empty string lambda expression in linq

Im having a foreach loop that looks like this:

foreach (var item in listOfFieldNames)
{
list.Where(s => s.GetType().GetProperty(item).GetValue(s, null).ToString().ToLower().Contains(searchString.ToLower()));
}


and it works pretty well, but whenever "s" is a null I get nullRefferenceException

I would like to change my s = null into s = " " but I don't know how to do it.
Could you guys help me?
Or maybe there is a method to skip that null record and continue my loop without getting an exception. That would also help me.

Trying to figure this out for quite some time and can't find the answer anywhere :/
Tried some .DefaultIfEmpty combinations but I don't think I know what to put inside it

Answer

If s comes null sometimes, you could use:

list.Where(s => s != null && s.GetType().GetProperty(item).GetValue(s, null).ToString().ToLower().Contains(searchString.ToLower()));
Comments