简体   繁体   English

可枚举包含可枚举

[英]Enumerable Contains Enumerable

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; } 对于一种方法,我具有以下参数IEnumerable<string> tags ,并且要查询对象列表,我们称它们为Post,其中包含属性IEnumerable<string> Tags { get; set; } IEnumerable<string> Tags { get; set; } IEnumerable<string> Tags { get; set; } . 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? 如何使用linq查询包含来自tags参数的所有标签的对象?

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. HashSet对此非常HashSet ,因为您可以在其中进行快速查找。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM