JP Hellemons JP Hellemons - 1 month ago 7
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) ||
p.SubCategoryName.Equals(s)).ToList();


Which is fine, until there is no
SubCategoryName

So I tried:

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


But if there is no
SubCategoryName
, 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
foreach


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
products
who have a null value in subcategory causing the first line to crash.

Answer

Simple suggestion: reverse the condition

s.Equals(p.SubCategoryName)

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