C# 字典无法从'&书信电报;匿名类型>';
这是我的密码:C# 字典无法从'&书信电报;匿名类型>';,c#,linq,group-by,C#,Linq,Group By,这是我的密码: var groupedDataDictionary = products .Where(p => p.ProductType == ProductType.ValueType) .GroupBy(p => (p.OfficeDebitId, p.OfficeDebitDate, p.PaymentMethod)) .ToDictionary(x => x.Key, x => x.Sum(p => p.Amount)); v
var groupedDataDictionary = products
.Where(p => p.ProductType == ProductType.ValueType)
.GroupBy(p => (p.OfficeDebitId, p.OfficeDebitDate, p.PaymentMethod))
.ToDictionary(x => x.Key, x => x.Sum(p => p.Amount));
var result = products.Select(p => new ResponseDto()
{
customer_id = p.CustomerId,
office_debit_date = p.OfficeDebitDate.Value.ToString(),
office_debit_id = p.OfficeDebitId.ToString(),
office_debit_total = groupedDataDictionary[new { p.OfficeDebitId, p.OfficeDebitDate, p.PaymentMethod }].Sum().ToString(), // this line causes error
payment_method = p.PaymentMethod.Value.ToString(),
}).ToList();
当在该行分配办公室\借方\总计时,它会显示:
错误CS1503参数1:无法从'
转换为'(字符串
OfficeDebitId,System.DateTime?OfficeDebitDate,
Enumerations.PaymentMethod?PaymentMethod)
您应该使用元组
或匿名类型
,但不要组合它们。如果要对键使用元组
,则还应使用元组
按键获取字典值:
var result = products.Select(p => new ResponseDto()
{
customer_id = p.CustomerId,
office_debit_date = p.OfficeDebitDate.Value.ToString(),
office_debit_id = p.OfficeDebitId.ToString(),
// Here you should use Tuple to get value by Key.
office_debit_total = groupedDataDictionary[(p.OfficeDebitId, p.OfficeDebitDate, p.PaymentMethod)].ToString(),
payment_method = p.PaymentMethod.Value.ToString(),
}).ToList();
还请注意,我删除了对方法Sum()
的调用,因为dictionarygroupedDataDictionary
已经包含聚合数据:x.Sum(p=>p.Amount)
我建议使用元组作为键。@John您能提供一个示例吗,如何?Thanksor使用值元组语法GroupBy(p=>(p.OfficeDebitId,p.OfficeDebitDate,p.PaymentMethod))
这个问题类似吗?@PavelAnikhouski这是另一个问题,无法添加重复的键,这就解决了