[英]Dictionary cannot convert from '<anonymous type>'
Here's my code:这是我的代码:
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();
When assiging office_debit_total
on that line it says:在该行上分配
office_debit_total
时,它说:
Error CS1503 Argument 1: cannot convert from
'<anonymous type: string OfficeDebiId, System.DateTime? OfficeDebitDate, Enumerations.PaymentMethod? PaymentMethod>'
错误 CS1503 参数 1:无法从
'<anonymous type: string OfficeDebiId, System.DateTime? OfficeDebitDate, Enumerations.PaymentMethod? PaymentMethod>'
'<anonymous type: string OfficeDebiId, System.DateTime? OfficeDebitDate, Enumerations.PaymentMethod? PaymentMethod>'
'<anonymous type: string OfficeDebiId, System.DateTime? OfficeDebitDate, Enumerations.PaymentMethod? PaymentMethod>'
to'(string OfficeDebitId, System.DateTime? OfficeDebitDate, Enumerations.PaymentMethod? PaymentMethod)'
'<anonymous type: string OfficeDebiId, System.DateTime? OfficeDebitDate, Enumerations.PaymentMethod? PaymentMethod>'
to'(string OfficeDebitId, System.DateTime? OfficeDebitDate, Enumerations.PaymentMethod? PaymentMethod)'
You should use either Tuples
or Anonymous Types
, but do not combine them.您应该使用
Tuples
或Anonymous Types
,但不要组合它们。 If you want to use Tuples
for keys then you should also use Tuples
to get dictionary values by keys:如果您想使用
Tuples
作为键,那么您还应该使用Tuples
通过键获取字典值:
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();
Also note that I deleted invocation of the method Sum()
, because dictionary groupedDataDictionary
already contains aggregated data: x.Sum(p => p.Amount)
.另请注意,我删除了方法
Sum()
的调用,因为字典groupedDataDictionary
已经包含聚合数据: x.Sum(p => p.Amount)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.