Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering a collection of items from contents of another collection

This used to work for me and then it failed. I want to return only those items that contain all the filters, not at least one filter as it is doing now. WHat is wrong here?

private IQueryable<IndexItem> FilteredIndex (IQueryable<IndexItem> index, IEnumerable<string> filters)

    {

        var filteredIndex= from f in filters.AsQueryable() 
               where f.Length>0
               from i in index 
               where i.FilterNames.Contains(f)
               select i;
        return filteredIndex;
   }
like image 439
zsharp Avatar asked Dec 07 '25 06:12

zsharp


1 Answers

Straight forward. For a given item from index check that it is true for all filters that the given item contains the filter. With this just select all items from index for that the given condition is true.

index.Where(item => 
   filters.All(filter => item.FilterNames.Contains(filter)))

I am not sure if the check for length greater than zero is required, nut it is easily integrated.

index.Where(item => 
   filters.All(filter =>
      (filter.Length > 0 ) || (item.FilterNames.Contains(filter))))

It works with LINQ to Objects and I guess it does what you want, but I am not sure if it works with LINQ to SQL.

like image 80
Daniel Brückner Avatar answered Dec 09 '25 01:12

Daniel Brückner