2014-05-04 59 views
0

在我的域中我有一個名爲「Block」的對象。一個「塊」可以有「引腳」和「屬性」附加到它。LINQ合併兩個分組查詢結果

我可以創建兩個組這給我下面的結果:

組別是:

Block:B1 
    Pin:P1 
    Pin:P2 
Block:B2 
    Pin:P3 
    Pin:P4 

第2組是:

Block:B1 
    Attribute:Att1, Value: Value1 
    Attribute:Att2, Value: Value2 
Block:B2 
    Attribute:Att3, Value: Value3 
    Attribute:Att4, Value: Value4 

現在我想合併這兩個結果的東西像這樣:

結果組是:

Block:B1 
    Pin:P1 
    Pin:P2 
    Attribute:Att1, Value: Value1 
    Attribute:Att2, Value: Value2 
Block:B2 
    Pin:P3 
    Pin:P4 
    Attribute:Att3, Value: Value3 
    Attribute:Att4, Value: Value4 

LINQ可以嗎?或者,我是否需要未分組的結果以後創建分組結果?

感謝

編輯: 隨着Road242解決方案,我得到這樣的結果:

Pin: P1 
Pin: P2 
Attribute: Att1 
Attribute: Att2 
Pin: P3 
Pin: P4 
Attribute: Att3 
Attribute: Att4 

的引腳和屬性看起來不錯,但我失去了塊作爲分組鍵:-(

編輯: 我的查詢看起來是這樣的:

var blockPinsQuery = from blockPinRelation in blockPinRelations 
      join block in blocks 
       on blockPinRelation.BlockId equals block.Id 
      join pin in pins 
       on blockPinRelation.PinId equals pin.Id 
      group pin by block 
      into g 
      select new 
        { 
         Block = g.Key, 
         Pins = g 
        }; 

var blockAttributesQuery = from blockAttributeRelation in blockAttributeRelations 
          join block in blocks 
           on blockAttributeRelation.BlockId equals block.Id 
          join attribute in stringAttributes 
           on blockAttributeRelation.AttributeId equals attribute.Id 
            group attribute by block 
           into g 
           select new 
           { 
            Block = g.Key, 
            Attributes = g 
           }; 

,你可以看到有一個關係表中的相關實體之間。但我猜這不重要。

我的輸出過程是這樣的:

foreach (var group in blockPinsQuery) 
     { 
      Console.WriteLine("Block:" + group.Block.Name); 
      group.Pins.ToList().ForEach(x => Console.WriteLine("\t" + "Pin:" + x.Name)); 
     } 

foreach (var group in blockAttributesQuery) 
     { 
      Console.WriteLine("Block:" + group.Block.Name); 
      group.Attributes.ToList().ForEach(x => Console.WriteLine("\t" + "Attribute:" + x.Name + ", " + "Value: " + x.Value)); 
     } 

和Road242查詢:

foreach (var group in joinedResults) 
     { 
      group.Pins.ToList().ForEach(p => Console.WriteLine("Pin: " + p.Name)); 
      group.Attributes.ToList().ForEach(p => Console.WriteLine("Attribute: " + p.Name)); 
     } 
+0

你能不能請張貼座的declartion,才能看到它的屬性等。由於使用 – Christos

+0

'Union'與強類型的回報,而不是匿名.. –

+0

@安德烈·菲格雷多:我試圖用聯盟()。正如你所提到的,Union()需要一個強類型化的返回值,但我不知道如何實現。我如何使用強類型返回值? –

回答