How to make WHERE IN in linq

So, I have a Blog object that has a list of tag objects ( List<Tag> ).

I am trying to create a method that accepts a list of tags and returns a list of blogs that contain all the tags in the submitted list.

I managed to create a method that will return a list of blogs if it matches a single tag but not a list of tags.

to do it i have it

 entities.Blogs.Where(b => b.Tags.Any(t => t.Name == tagName)) 

But I can't figure out how to do something like this

 entities.Blogs.Where(b => b.Tags.Any(t => t.Name == tags[0] AND t.Name == tags[1] AND t.Name == tags[2] etc.......)) 

Is there any way to do this?

Thanks!

I am using LINQ to Entities

+6
c # linq
source share
2 answers

Logically, I think you need something like:

 entities.Blogs.Where(b => tags.All(t => b.Tags.Any(bt => bt.Name == t))) 

As an alternative:

 HashSet<string> tagNames = new HashSet<string>(tags); return entities.Blogs .Where(b => tagNames.IsSubsetOf(b.Tags.Select(x => x.Name))); 

If this uses LINQ to Entities, I doubt it will work, but it should work if you just use LINQ to Objects. Even then, it will not be terribly effective. I suspect there is a more efficient way to do something, but I can't think about it right away ... it looks like you want to join, but then it gets harder again.

+11
source share

You can do something like this:

 List<Tag> tags = GetTags...; IQueryable<Blog> blogs = entities.Blogs; // start with all foreach(var tag in tags){ var thisTag = tag; //this is needed to prevent a bug blogs = blogs.Where(entry=>entry.Tags.Any(entryTag=>entryTag.TagId==thisTag.TagId)); } return blogs.OrderBy....; 

This will result in a pool of Where clauses requiring all tags to be present for the blog entry to be returned.

+1
source share

All Articles