tags:

views:

98

answers:

5

For a method I have the following parameter IEnumerable<string> tags and with to query a list of objects, let's call them Post, that contains a property IEnumerable<string> Tags { get; set; }.

My question is:
How do I use linq to query for objects that contains all the tags from the tags parameter?

private List<Post> posts = new List<Post>();

public IEnumerable<Post> GetPostsWithTags(IEnumerable<string> tags)
{
  return ???;
}
A: 

Check out http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx, maybe you can find some sample code there.

Chris Richner
+3  A: 
return posts.Where(post => tags.All(post.Tags.Contains))
Kobi
This returns a list of booleans, not a list of Posts. EDIT: your edit fixed it, looking good now.
Jakob
@Jakob - Good catch, thanks.
Kobi
+1  A: 

First, realise the parameter into a collection, so that you don't risk re-quering it if it happens to be an expression and not a concrete collection, as that could give horribly bad performance or even fail to work. A HashSet is good for this, as you can do fast look-ups in it.

Then check that all tags from each item exist in the set:

public IEnumerable<Post> GetPostsWithTags(IEnumerable<string> tags) {
  HashSet<string> tagSet = new HashSet(tags);
  return posts.Where(p => p.Tags.Count(t => tagSet.Contains(t)) == tags.Count);
}
Guffa
+3  A: 
public IEnumerable<Post> GetPostsWithTags(IEnumerable<string> tags)
{
  return posts.Where(post => tags.All(tag => post.Tags.Contains(tag)));
}
Jakob
+1  A: 
var postsWithTags = posts.
    Where(p => !tags.Except(p.Tags).Any());
Lee