Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a website containing news stories. 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 stories that have one or more tags in common with the list of tags on the current page. I have written some Linq code that compares a single tag to the tags on each of the news stories but I need to extend it so that it works with a list of tags.

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

What I want to do is replace currentTag with a list of tags. The list can contain between 1 and 6 tags. Can anyone help?

like image 957
fillostein Avatar asked Apr 24 '15 08:04

fillostein


1 Answers

You can use Intersect + Any:

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

This presumes that Tags actually is an IEnumerable<string>or another type that overrides Equals + GetHashCode. If that's not the case you can provide a custom IEqualityComparer<Tag> for Intersect.

So tagList is the List<string> of the curent-page as requested. But if you want to list all which have one or more tags in common with the list of tags on all pages, so an IEnumerable<List<string>>, you could use SelectMany to flatten them:

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

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

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

This is less efficient in LINQ-To-Objects since it's not using a set.

like image 57
Tim Schmelter Avatar answered Oct 09 '22 04:10

Tim Schmelter