2009-01-14 98 views
21

如何使用LINQ爲下表創建嵌套分組?我想按Code分組,然後按Mktcode分組。如何使用LINQ創建嵌套的分組字典?

Code Mktcode Id 
==== ======= ==== 
1 10  0001 
2 20  0010 
1 10  0012 
1 20  0010 
1 20  0014 
2 20  0001 
2 30  0002 
1 30  0002 
1 30  0005 
喜歡

我一本字典,最終,像

Dictionary<Code, List<Dictionary<Mktcode, List<Id>>>> 

所以這本字典的值將

{1, ({10,(0001,0012)}, {20,(0010,0014)}, {30, (0002, 0005)})}, 
{2, ({20,(0001, 0010)}, {30, (0020)})} 

回答

26

我倒是覺得它是這樣的:

  • 你主要通過代碼分組,這樣做第一
  • 對於每個組,你仍然有結果的列表 - 所以應用其他在那裏分組。

喜歡的東西:

var groupedByCode = source.GroupBy(x => x.Code); 

var groupedByCodeAndThenId = groupedByCode.Select(group => 
    new { Key=group.Key, NestedGroup = group.ToLookup 
             (result => result.MktCode, result => result.Id)); 

var dictionary = groupedByCodeAndThenId.ToDictionary 
    (result => result.Key, result => result.NestedGroup); 

這會給你一個Dictionary<Code, Lookup<MktCode, Id>> - 我認爲這就是你想要的。這完全沒有經過測試。

+5

Geez,你是對的。你的精神力量簡直令人難以置信。 – Graviton 2009-01-14 13:23:43

16

您可以構建字典<的查找(種,列表< >>)使用group by into

var lines = new [] 
{ 
    new {Code = 1, MktCode = 10, Id = 1}, 
    new {Code = 2, MktCode = 20, Id = 10}, 
    new {Code = 1, MktCode = 10, Id = 12}, 
    new {Code = 1, MktCode = 20, Id = 10}, 
    new {Code = 1, MktCode = 20, Id = 14}, 
    new {Code = 2, MktCode = 20, Id = 1}, 
    new {Code = 2, MktCode = 30, Id = 2}, 
    new {Code = 1, MktCode = 30, Id = 2}, 
    new {Code = 1, MktCode = 30, Id = 5}, 
}; 

var groups = from line in lines 
    group line by line.Code 
    into codeGroup 
    select new 
    { 
     Code = codeGroup.Key, 
     Items = from l in codeGroup 
      group l by l.MktCode into mktCodeGroup 
      select new 
      { 
       MktCode = mktCodeGroup.Key, 
       Ids = from mktLine in mktCodeGroup 
        select mktLine.Id 
      } 
    }; 
+0

有關如何將組轉換爲字典類型的任何想法? – Graviton 2009-01-14 10:35:30

+5

groups.ToDictionary(g => g.Key,g => g.ToList()) – 2009-01-14 13:34:37

12

以下是我會做:

Dictionary<Code, Dictionary<MktCode, List<Id>>> myStructure = 
    myList 
    .GroupBy(e => e.Code) 
    .ToDictionary(
     g => g.Key, 
     g => g 
     .GroupBy(e => e.Mktcode) 
     .ToDictionary(
      g2 => g2.Key, 
      g2 => g2.Select(e => e.Id).ToList() 
     ) 
    ) 

這裏的進程的失敗:

集團通過代碼元素,並創建一個外字典,其中最關鍵的是代碼。

​​

對於外部字典中的每個鍵,通過Mktcode重新分組元素並創建一個內部字典。

 g => g 
     .GroupBy(e => e.Mktcode) 
     .ToDictionary(
      g2 => g2.Key, 

對於內部詞典中的每個鍵,投影這些元素的id並將其轉換爲列表。

  g2 => g2.Select(e => e.Id).ToList() 
     ) 
    )