Home > Enterprise >  How to check if the property of a class(collection/enumeration of classes) matches to an item from a
How to check if the property of a class(collection/enumeration of classes) matches to an item from a

Time:09-17

I have a class Product

public Guid Id { get; set; }
    
public string Name { get; set; }
    
public string Color { get; set; }

Color can be a string like "Blue, Red, Green" or "Red, Brown" etc.

And I have a collection or enumeration of these classes for instance

Ienumerable<Product> Products

Also I have another string collection of colors like

List<string> colorsForFiltering = new List<string>() { Blue, Yellow, Brown}

How can I filter Product using Color property throw linq query? I tried several options including

Products = Products.Where(x => colorsForFiltering.Contains(x.Color));

and many others. I know that this query is wrong. I'm sure i can solve this problem using cycles. But i wanted to know if it is possible to do that using linq. Unfortunately I cant find the answer. Thank you in advance!

CodePudding user response:

Ideally you should change Color to an IEnumerable<string>, but with what you have you can do:

Products = Products.Where(x => colorsForFiltering.Intersect(x.Color.Split(',', StringSplitOptions.TrimEntries).Any());

Note that this will almost certainly not be translatable to SQL so you'll have to do it in memory. An alternative that is SQL-translatable would be to loop through the filter colors:

var results = colorsForFiltering.SelectMany(c=>
        Products.Where(x => x.Color.Contains(c))
    );

This is not foolproof either, since if you have any colors that are substrings of another color (e.g. "Blue-Green", then Contains will match the substring, but it is translatable to SQL

CodePudding user response:

Johnathan Barclay in comments solved the issue

x => colorsForFiltering.Any(x.Color.Contains)

i just used All instead of Any

  • Related