Linq where contains ALL elements in the list

I have a list of filters, and I want to use it to query a table in which the returned items contain ALL values ​​not only 1.

For example, I have a label / tag system. I want to return records that have the tags “sport” and “football”. However, “sport” and “football” are stored in the list and can be any other tags that the user provides.

I use the framework entity. I have a table of tags, teams, TeamTags. My current request is this:

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 tag “sport”, and not those that are designated as “sport” and “football”.

If you intend to type the tag "sport", first get a list of teams from all sports. Then you add the “soccer” tag, which will be filtered even more for football teams. Therefore, my code above basically does OR in that place. I also want to be able to do AND.

Thus, an example of data in a database would be:

The Broncos has sports and football tags The Mets has sports and baseball tags

I want the team to have sports and soccer tags, not sports or soccer tags.

+4
source share
2 answers

I suggest trying:

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

, , ( , , - ):

var teamNames = teams.Select(t => t.Name).ToList();
+8
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();

0

All Articles