2017-02-22 85 views
0

我想使用Linq執行嵌套GroupBy,我無法讓它工作。我的代碼如下:嵌套GroupBy使用Linq

var summaryFile = new RemittanceCenterFilesSummaryListModel 
     { 
      RemittanceFilesSummary = remittanceCenterSummaryListModel.RemittanceBatchSummaryRecord.GroupBy(x => new { x.FileId, x.SourceFileName }) 
       .Select(x => new RemitanceCenterFileSummarizedModel 
       { 
        FileId = x.Key.FileId, 
        SourceFileName = x.Key.SourceFileName, 
        Batches = x.ToList().GroupBy(b => new { b => b.BatchCode }) 
         .Select(c => new RemittanceCenterBatchSummarizedModel 
         { 
          FileId = x.Key.FileId, 
          SourceFileName = x.Key.SourceFileName, 
          BatchCode = c.Key, 
          BatchType = c.Key, 
          DetailRecordCountAdc = x.Count(y => y.BillingSystemCode == BillingSystemCode.Adc), 
          DetailRecordCountNotAdc = x.Count(y => y.BillingSystemCode == BillingSystemCode.Exceed), 
          AmountAdc = x.Where(y => y.BillingSystemCode == BillingSystemCode.Adc).Sum(y => y.PaymentAmount), 
          AmountNotAdc = x.Where(y => y.BillingSystemCode == BillingSystemCode.Exceed).Sum(y => y.PaymentAmount), 
          AmountTotal = x.Sum(y => y.PaymentAmount), 
         }); 
        ScannedBatchCount = x.Count(y => y.BatchType == "S"), 
        ScannedBatchAmount = x.Where(y => y.BatchType == "S").Sum(y => y.PaymentAmount), 
        NonScannedBatchCount = x.Count(y => y.BatchType != "S"), 
        NonScannedBatchAmount = x.Where(y => y.BatchType != "S").Sum(y => y.PaymentAmount), 
       }).ToList() 
     }; 

第一的GroupBy工作正常,但是當我嘗試GROUPBY批次場,我發現了以下生成錯誤:

錯誤76無效的匿名類型成員聲明。匿名類型成員必須聲明爲成員分配,簡單名稱或成員訪問權限。

錯誤在這裏強調:

Batches = x.ToList().GroupBy(b => new { b => b.BatchCode }) 

有什麼建議?

+0

嘗試'.GroupBy(b => new {BatchCode = b.BatchCode})' – slawekwin

回答

2

你的意思是

Batches = x.ToList().GroupBy(b => b.BatchCode) 

沒有必要,如果你想通過組只有一個屬性,以創建一個匿名類型。


如果你需要一個匿名類型,語法將

Batches = x.ToList().GroupBy(b => new { b.BatchCode }) 

你使用其他運營商的λ(b => new {b => b.BatchCode})匿名類型裏面,這是無效的。

+0

感謝您的迴應! – Jason