JP Hellemons JP Hellemons - 8 months ago 32
C# Question

Linq conditional where only when prop is not null

I have this line:

products = products.Where(p => p.Brand.Equals(s) ||
p.CatCodeNaam.Equals(s) ||

Which is fine, until there is no

So I tried:

var t = products.Where(p => p.Brand.Equals(s) ||
.Where(p => !string.IsNullOrWhiteSpace(p.SubCategoryName) && p.SubCategoryName.Equals(s));

But if there is no
, it should just ignore it and do not filter so no empty collection.
I am sorry but I can't seem to focus enough this Friday to solve such a simple Linq statement.

I know that I can fix it by having the database returning an empty string
isnull(SubCategoryName,'') as SubCategoryName
but I do not want that. I am looking for a Linq fix.

edit I think that I might have to add some test data to explain my issue more.

I have an array with keywords like:
"car", "ford", "focus"
and I iterate over the keyword array with a

and since I do not know if the keyword is a brand, category or subcategory I have to check if it is one of them.
But there are objects in the dataset
who have a null value in subcategory causing the first line to crash.


Simple suggestion: reverse the condition


That way it won't matter if p.SubCategoryName is null