2013-05-27 43 views
1

我有以下類:LINQ如何GROUPBY正確

class AssembledDTO 
{ 
    int pid, 
    int blockId, 
    List<string> references 
} 

我想組通過一切方式如下:

AssembledParts.GroupBy(entry => new 
         { 
          entry.PID, 
          entry.BlockId 
         }). 
         Select((key , val)=> new AssembledDTO 
          { 
           BlockId = key.Key.BlockId, 
           PID = key.Key.PID, 
           References = val. 
          }) 

References我想加在一起都references名單我分組的每個羣組。

我該怎麼做?我在這裏想念什麼?

+0

你試過'References = key.ToList()'嗎? – I4V

+0

@ I4V我沒有看到那裏ToList() –

+0

請不要重新發布! http://stackoverflow.com/q/16773147/861716替代編輯您的問題。 –

回答

2

SelectMany應該訣竅來平坦化結果。

AssembledParts.GroupBy(entry => new 
        { 
         entry.PID, 
         entry.BlockId 
        }). 
        Select(key => new AssembledDTO 
         { 
          BlockId = key.Key.BlockId, 
          PID = key.Key.PID, 
          References = key.SelectMany(v => v.references).ToList(); 
         }) 
+1

Downvoter - 你會給我一些關於這個答案有什麼問題的提示嗎?我沒有測試過它,但似乎是Night Walker正在尋找的東西。如果我犯了錯 - 我想知道並糾正自己。 – Pako