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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With