开发者

Enumerable Contains Enumerable

For a method I have the following parameter IEnumerable<string> tags and with to开发者_JS百科 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 ???;
}


public IEnumerable<Post> GetPostsWithTags(IEnumerable<string> tags)
{
  return posts.Where(post => tags.All(tag => post.Tags.Contains(tag)));
}


return posts.Where(post => tags.All(post.Tags.Contains))


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);
}


var postsWithTags = posts.
    Where(p => !tags.Except(p.Tags).Any());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜