Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用ALL的LINQ查询_C#_Linq - Fatal编程技术网

C# 使用ALL的LINQ查询

C# 使用ALL的LINQ查询,c#,linq,C#,Linq,想象一下一个照片标签系统 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"},

想象一下一个照片标签系统

    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();
我是否可以使用LINQ操作符来实现这一点

photos.Where(p => t.Tags.Contain(tags[0]) && t.Tags.Contains(tag[1]));
很难知道操作员
标签
有什么功能。

确定:

// All the tags in "tags" are contained in p.Tags
var results = photos.Where(p => tags.All(tag => p.Tags.Contains(tag)));

编辑:注意,这假设在现实中,您在标记上有一个适当的平等实现。否则,您将需要以下内容:

var results = photos.Where(p => !tags.Select(t => t.Name)
                                     .Except(p.Tags.Select(t => t.Name)).Any());

标记名不匹配(这将是byref操作),我假设他需要灵活地扩展到>2个标记。
标记[0]
应该是
标记[1]
?他可能希望标记名匹配……但是,容器不会进行对象比较吗?@jvenema:Edited。让标记实现
IEquatable
可能更好。实际上,我创建了一个
IEqualityComparer
,并在
Contains()
第二个参数中删除了它。谢谢你的回答!
// 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());
var results = photos.Where(p => !tags.Select(t => t.Name)
                                     .Except(p.Tags.Select(t => t.Name)).Any());