简体   繁体   中英

linq where contains ALL items in list

I have a list of filters and I want to use it to query a table where the returned items contain ALL of the values not just 1.

For example I have a label/tag system. I want to return records that have the tag 'sport' AND 'football' in them. However 'sport' and 'football' are stored in a list and could be any number of other tags that the user supplies.

I'm using entity framework. I have a Tags, Teams, TeamTags table. My current query is as such:

string _tags = "sport,football";
List<string> tags = _tags.Split(',').ToList();

var teams = (from t in db.Tags where tags.Contains(t.TagName) select t.Teams).FirstOrDefault().Select(i => i.TeamNames).ToList()

But this will return all teams that have the 'sport' tag not those that are labeled as 'sports' AND 'football' only.

If you imagine typing the 'sport' tag first you'd get a list of teams from all sports. Then you add the 'football' tag that list would be filtered even more to just the football teams. So my code above basically does an OR in the where. I want the ability to do an AND as well.

So example data in the database would be:

Broncos has sport and football tags Mets has sport and baseball tags

I want the team that has sport AND football tags, not sport OR football tags.

I would suggest giving this a try:

var teams = (from team in db.Teams 
             where tags.All(tag => team.Tags.Any(ttag => ttag.TagName == tag))
             select team).ToList();

From there, if you want a list of the names, you can do a projection on that (it's hard to entirely grok how your data structures are set up, but something like this):

var teamNames = teams.Select(t => t.Name).ToList();
string _tags = "sport,football";
List<string> tags = _tags.Split(',').ToList();

var teams = (from t in db.Tags where tags.All(x=> x.Contains(t.TagName)) select t.Teams).FirstOrDefault().Select(i => i.TeamNames).ToList();

This should help get you the desired result

I know it's kinds lame, but to get EF core working, and return only elements where a collection suppose to contain all elements I had to do something like this:

            // var query = context....;

            foreach (var tag in tags)
            {
                query = query.Where(p => p.TagList.Any(t => t == tag));
            }

            return query;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM