2011-07-24 47 views
2

我有一套我想在Linq中分組的對象。然而,我想要使用的密鑰是多個密鑰的組合。對於如可以將相同的對象添加到LINQ中的多個組中嗎?

Object1: Key=SomeKeyString1 

Object2: Key=SomeKeyString2 

Object3: Key=SomeKeyString1,SomeKeyString2 

現在,我想結果是隻有兩組

Grouping1: Key=SomeKeyString1 : Objet1, Object3 

Grouping2: Key=SomeKeyString2 : Object2, Object3 

基本上我想相同的對象是兩個羣體的一部分。 Linq有可能嗎?

回答

4

那麼,不是直接GroupByGroupJoin。這兩者都從一個對象中提取單個分組鍵。但是,你可以這樣做:

from groupingKey in groupingKeys 
from item in items 
where item.Keys.Contains(groupingKey) 
group item by groupingKey; 

示例代碼:

using System; 
using System.Collections.Generic; 
using System.Linq; 

class Item 
{ 
    // Don't make fields public normally! 
    public readonly List<string> Keys = new List<string>(); 
    public string Name { get; set; } 
} 

class Test 
{ 
    static void Main() 
    { 
     var groupingKeys = new List<string> { "Key1", "Key2" }; 
     var items = new List<Item> 
     { 
      new Item { Name="Object1", Keys = { "Key1" } }, 
      new Item { Name="Object2", Keys = { "Key2" } }, 
      new Item { Name="Object3", Keys = { "Key1", "Key2" } }, 
     }; 

     var query = from groupingKey in groupingKeys 
        from item in items 
        where item.Keys.Contains(groupingKey) 
        group item by groupingKey; 

     foreach (var group in query) 
     { 
      Console.WriteLine("Key: {0}", group.Key); 
      foreach (var item in group) 
      { 
       Console.WriteLine(" {0}", item.Name); 
      } 
     } 
    } 
} 
相關問題