Reputation: 87
I'm trying to perform a nested GroupBy using Linq and I'm not able to get it to work. My code is the following:
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()
};
The first GroupBy is working correctly, however when I try to GroupBy the Batches field I'm getting the following build error:
Error 76 Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.
The error is highlighted here:
Batches = x.ToList().GroupBy(b => new { b => b.BatchCode })
Any suggestions ?
Upvotes: 0
Views: 141
Reputation: 43886
You mean
Batches = x.ToList().GroupBy(b => b.BatchCode)
There is no need to create an anonymous type if you want to group by only one property.
If you need an anonymous type, the syntax would be
Batches = x.ToList().GroupBy(b => new { b.BatchCode })
you used another lambda operator (b => new {b => b.BatchCode}
) inside the anonymous type, which was invalid.
Upvotes: 2