LINQ分组到字典会导致错误

问题描述 投票:0回答:1

我需要按多列分组并求和。

我在这里使用字典:

office_debit_total = p.OfficeEnum == SomeEnum.ValueType ? p.OfficeAmount.ToString() : totalAmounts[p.OfficeDebitId].ToString(),

这是我尝试过的:

Dictionary<string, decimal> totalAmounts = products
    .Where(p => p.ProductType == ProductType.ValueType)
    .GroupBy(p => new { p.OfficeDebitId, p.OfficeDebitDate, p.PaymentMethod }) 
    .ToDictionary(x => (x.Key.OfficeDebitId, x.Key.OfficeDebitDate, x.Key.PaymentMethod), x => x.Sum(p => p.Amount));

但是我收到一个错误:

错误CS0029无法隐式转换类型'System.Collections.Generic.Dictionary “到'System.Collections.Generic.Dictionary'

这里怎么了?我在这里想念的是什么?我尝试将.GroupBy(p => new { p.OfficeDebitId, p.OfficeDebitDate, p.PaymentMethod })更改为Tuple,但这是相同的。也许我应该更改.ToDictionary(x =>部分?还是?

看起来很简单,我需要按这三个属性对数据进行分组,但实际上不起作用

任何帮助都会很棒!

谢谢

欢呼声

c# linq group-by linq-to-sql
1个回答
0
投票

使其可变

var totalAmounts = products
    .Where(p => p.ProductType == ProductType.ValueType)
    .GroupBy(p => new { p.OfficeDebitId, p.OfficeDebitDate, p.PaymentMethod }) 
    .ToDictionary(x => (x.Key.OfficeDebitId, x.Key.OfficeDebitDate, x.Key.PaymentMethod), x => x.Sum(p => p.Amount));

然后单击黄色灯泡(快速操作)并使用选择“使用显式类型而不是'var'”

© www.soinside.com 2019 - 2024. All rights reserved.