Imagine a photo tagging system...
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();
And this line:
var results = //return photos when Photo.Tags contains BOTH tags
Is there a LINQ operator I can use to achieve this?
Sure:
// All the tags in "tags" are contained in p.Tags
var results = photos.Where(p => tags.All(tag => p.Tags.Contains(tag)));
or
// 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());
EDIT: Note that this assumes that in reality you've got an appropriate equality implementation on Tag. Otherwise you'll need something like:
var results = photos.Where(p => !tags.Select(t => t.Name)
.Except(p.Tags.Select(t => t.Name)).Any());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With