2009-07-07 105 views
1

我有這個查詢工作,但它不返回到我正在尋找的。Linq到對象嵌套組 - 由

我的集合:

List<TransactionRecord> transactionLog; 

TransactionRecord簡化看起來是這樣的:

class TransactionRecord { 
    public string txSetComments; 
    public string BatchComments; 
    public string TargetComments; 
    public string TargetName; 
    public string TargetValue; 
} 

,並可能被初始化爲:

List<TransactionRecord> transactionLog = new List<TransactionRecord>() 
{  
    new TransactionRecord { txSetComments = "txc1", 
          BatchComments = "bc1", 
          TargetComments = "tc1", 
          TargetName = "target1", 
          TargetValue = "v1" }, 

    new TransactionRecord { txSetComments = "txc1", 
          BatchComments = "bc1", 
          TargetComments = "tc1", 
          TargetName = "target1", 
          TargetValue = "v2" }, 

    new TransactionRecord { txSetComments = "txc2", 
          BatchComments = "bc2", 
          TargetComments = "tc1", 
          TargetName = "target2", 
          TargetValue = "v3" }, 

    new TransactionRecord { txSetComments = "txc2", 
          BatchComments = "bc1", 
          TargetComments = "tc1", 
          TargetName = "target2", 
          TargetValue = "v4" }, 

    new TransactionRecord { txSetComments = "txc1", 
          BatchComments = "bc3", 
          TargetComments = "tc1", 
          TargetName = "target1", 
          TargetValue = "v5" }, 

    new TransactionRecord { txSetComments = "txc3",  
          BatchComments = "bc3", 
          TargetComments = "tc1", 
          TargetName = "target3", 
          TargetValue = "v6" }   
}; 

下面是該查詢至今:

Dictionary<string, Dictionary<string, IEnumerable<TransactionRecord>>> history = 
    transactionLog.GroupBy(tx => tx.TxSetComments) 
     .ToDictionary(g => g.Key, 
         g => g.GroupBy(b => b.BatchComments).ToDictionary(e => e.Key, 
                     e => e.Where(t => t.TargetName == Target))); 

這是問題所在。如果我在查詢中設置「目標」到「目標1」,大部分的結果是我所期望的:

txc1 
    bc1 
     target1/v1 
     target1/v2 
    bc3 
     target1/v5 

這是一個良好的開端,但我也得到:加入

txc2 
txc3 

到列表中的一個完整的結果,看起來喜歡就好:

txc1 
    bc1 
     target1/v1 
     target1/v2 
    bc3 
     target1/v5 
txc2 
txc3 

我想查詢只返回頂級組,如果有一個匹配的「目標」。在上面的例子中,即使它們與「目標」不匹配,它仍然返回「txc2」和「txc3」作爲頂級組。

我希望這不是太混亂。任何建議?

謝謝!

回答

2

將您的Where子句複製到GroupBy的外部。

var history = transactionLog.Where(record => record.TargetName == "target1") 
    .GroupBy(tx => tx.txSetComments) 
    .ToDictionary(
     g => g.Key, 
     g => g.GroupBy(b => b.BatchComments) 
       .ToDictionary(e => e.Key, 
          e => e.Where(t => t.TargetName == "target1")); 
+0

啊,是的,現在它是如此明顯。這是我沒有試過的一個.Where條款。令人驚訝的是,我們在盯着幾個小時的嵌套LINQ查詢後變得多麼盲目。 謝謝! – IUnknown 2009-07-07 02:56:21