Using Linq to compare a list with a list of lists in C #

I have a website containing news. Each story has a list of tags associated with it. Other pages on the site also have a list of tags. On one of the other pages I want to list all the news containing one or more tags along with a list of tags on the current page. I wrote some Linq code that compares one tag with tags on each of the news, but I need to expand it to work with a list of tags.

query = query.Where(x => x.Tags.Contains(currentTag)); 

I want to replace currentTag with a list of tags. The list can contain from 1 to 6 tags. Can anyone help?

+5
source share
1 answer

You can use Intersect + Any :

 query = query.Where(x => x.Tags.Intersect(tagList).Any()); 

This suggests that Tags actually an IEnumerable<string> or other type that overrides Equals + GetHashCode . If this is not the case, you can provide a custom IEqualityComparer<Tag> for Intersect .

So tagList is a List<string> for the current page. But if you want to list all those that have one or more tags along with a list of tags on all pages, so IEnumerable<List<string>> , you can use SelectMany to flatten them:

 query = query.Where(x => x.Tags.Intersect(allTagLists.SelectMany(list => list)).Any()); 

If Intersect not supported by your LINQ provider, you can use the following approach:

 query = query.Where(x => x.Tags.Any(t => tagList.Contains(t))); 

This is less efficient in LINQ-To-Objects since it does not use a set.

+7
source

All Articles