Filtering a collection of items from the contents of another collection

It worked for me, and then it didn’t work. I want to return only those elements that contain all the filters, and not at least one filter, as it is 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;
   }
+3
source share
3 answers

How about something like:

foreach(string s in filters) {
    if(s.Length == 0) continue;
    string tmp = s; // because of "capture" problem
    index = index.Where(i => i.FilterNames.Contains(tmp));
}
return index;

This applies a sequence of sentences Wherecovering all filters - essentially AND.

+1
source

Straight ahead. For a given element from the index, check that for all filters it is true that this element contains a filter. In this case, simply select all the elements from the index for which this condition is true.

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

, , .

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

LINQ to Objects, , , , , LINQ to SQL.

+3

Rotate it. What you want is those elements in the index where each element in FilterNames has a corresponding entry in the filters. I'm not sure how good that would be, but you need to compare the score. Sort of:

private IQueryable<IndexItem> FilteredIndex(IQueryable<IndexItem> index, IEnumerable<string> filter)
{
    var filteredIndex = from i in index
                        where (from s in i.FilterNames
                               where filter.Contains(s)
                               select s).Count() == i.FilterNames.Count
                        select i;
    return filteredIndex;
}
+1
source

Source: https://habr.com/ru/post/1705824/


All Articles