想象一下照片标签系统......
public class Photo
{
public IList<Tag> Tags {get;set;}
}
public class Tag
{
public string Name {get;set;}
}
IList<Tag> tags = new [] {
new Tag{Name = "tag1"},
new Tag{Name = "tag2"}
};
IList<Photo> photos = GetAllPhotos();
Run Code Online (Sandbox Code Playgroud)
这一行:
var results = //return photos when Photo.Tags contains BOTH tags
Run Code Online (Sandbox Code Playgroud)
我可以使用LINQ运算符来实现这一目标吗?
Jon*_*eet 11
当然:
// All the tags in "tags" are contained in p.Tags
var results = photos.Where(p => tags.All(tag => p.Tags.Contains(tag)));
Run Code Online (Sandbox Code Playgroud)
要么
// All the "tags" except the ones in p.Tags ends up as an empty set
var results = photos.Where(p => !tags.Except(p.Tags).Any());
Run Code Online (Sandbox Code Playgroud)
编辑:请注意,这假设实际上你在Tag上有一个适当的相等实现.否则你需要这样的东西:
var results = photos.Where(p => !tags.Select(t => t.Name)
.Except(p.Tags.Select(t => t.Name)).Any());
Run Code Online (Sandbox Code Playgroud)