Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Query Using ALL

Tags:

c#

linq

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?

like image 778
mxmissile Avatar asked Mar 20 '26 10:03

mxmissile


1 Answers

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());
like image 88
Jon Skeet Avatar answered Mar 21 '26 22:03

Jon Skeet