LINQ query with ALL

Imagine a photo labeling 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

Can I use a LINQ statement for this?

+2
source share
2 answers

Of course:

// 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: Please note that this assumes that you actually have a matching equality implementation in Tag. Otherwise, you will need something like:

var results = photos.Where(p => !tags.Select(t => t.Name)
                                     .Except(p.Tags.Select(t => t.Name)).Any());
+11
source
photos.Where(p => t.Tags.Contain(tags[0]) && t.Tags.Contains(tag[1]));

Its hard to know which operators Taghave.

0
source

Source: https://habr.com/ru/post/1726896/


All Articles