tags:

views:

96

answers:

2

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

I'm trying to create a method that takes a list of tags and returns a list of blogs that contain all the tags in the passed in list.

I was able to make a method that will return a list of blogs if it matches one tag, but not a list of tags.

to do that I have this

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?

Thank you!

I'm using LINQ to Entities

+7  A: 

Logically, I think you want something like:

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

Alternatively:

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

If this is using LINQ to Entities, I doubt that this will work - but it should work if you're just using LINQ to Objects. Even then, it's not going to be terribly efficient. I suspect there's a more efficient way of doing things, but I can't immediately think of it... it feels like you want a join, but then it gets tricky again.

Jon Skeet
Jon Skeet is the MAN! Thank you JS. The first option worked out great.
hanesjw
+1  A: 

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 chain together the Where clauses to require that all the Tags be present for a blog entry to be returned.

Andrew Barber