2011-07-24 50 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); 
      } 
     } 
    } 
} 
相关问题