2009-07-07 7 views
1

이 쿼리는 작동하지만 찾고있는 것을 정확히 반환하지 않습니다.Linq to objects 중첩 된 그룹 by

나는 모음이 있습니다 단순화

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))); 

여기에 문제가 있습니다.

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

이 좋은 시작이다, 그러나 나는 또한 얻을 : 내가 쿼리에서 "대상"을 설정하면 "이 target1"에, 결과의 대부분은 내가 기대하는 것 같다

txc2 
txc3 

추가 처럼 좋아 보이는 완벽한 결과에 대한 목록 : 일치에 "대상"이 경우에만 최상위 그룹을 반환에

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

나는 쿼리를하고 싶습니다. 위의 예에서 "txc2"및 "txc3"은 "대상"과 일치하지 않더라도 최상위 그룹으로 반환합니다.

너무 혼란스럽지 않기를 바랍니다. 어떤 추천?

감사합니다.

답변

2

GroupBy 밖에서 Where 절을 복사하십시오.

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

아, 그렇습니다. 지금은 분명합니다. 그것이 하나입니다. 어디에서 절을하려고하지 않았습니다. 놀랍게도 몇 시간 동안 중첩 된 linq 쿼리를 응시 한 후 어떻게 눈이 어두워 지는지 감사합니다. – IUnknown