0

Trying to work out this lambda query without doing a foreach etc. I currently have a database table with a column which contains a comma separated list of strings. It's basically a filter (it could for example be 'pants,tops,t-shirts,gloves'). In the function that queries the database is basically has a parameter that accepts a similar string.

I don't know if I'm just too tired at the moment and can't work it out but struggling. I know it will be Intersect but can't figure out the syntax.

Currently I have...

    public static List<ItemListItem> GetItems(string filter = "")
    {
        var db = new dbConnection();

        var results = (from i in db.Items
                       select i);

        if (!string.IsNullOrEmpty (filter))
            results = results.Where(x => x.Filters.Split(',').Intersect(filter.Split(',')) )

    }

1 Answers1

2

You need Enumerable.Any at the end of your Intersect like:

x.Filters.Split(',').Intersect(filter.Split(',')).Any()

So your query would be:

results = results.Where(x => x.Filters.Split(',')
    .Intersect(filter.Split(','))
    .Any()); 

Enumerable.Where would require an expression returning bool. Intersect would return an IEnumerable<T> and Enumerable.Where would not accept it. Adding Enumerable.Any would means return those rows where intersection resulted in Any row.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
Habib
  • 219,104
  • 29
  • 407
  • 436