2011-09-02 75 views
2

想象中的照片標籤系統...LINQ查詢使用ALL

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(); 

這行:

var results = //return photos when Photo.Tags contains BOTH tags 

是否有一個LINQ操作我可以用它來實現這一目標?

回答

11

肯定的:

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

// 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()); 
+0

哈哈,你太快了! –

+1

他可能想要標籤名稱上的匹配,儘管...不會做包含對象的比較嗎? – jvenema

+1

@jvenema:編輯。這可能會更好地使Tag實現'IEquatable ' –

0
photos.Where(p => t.Tags.Contain(tags[0]) && t.Tags.Contains(tag[1])); 

它很難知道運營商Tag有什麼。

+1

將不匹配的標籤名稱(這將是一個byref操作),我假設他需要它是靈活的擴大到> 2標籤。 – jvenema

+0

'tag [0]'應該是'tags [1]'? –

+0

你是對的@Jvenema。 – mxmissile