【问题标题】:Dictionary cannot convert from '<anonymous type>'字典无法从“<匿名类型>”转换
【发布时间】:2020-08-26 18:49:43
【问题描述】:

这是我的代码:

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();

当在该行上分配 office_debit_total 时,它会说:

错误 CS1503 参数 1:无法从 '<anonymous type: string OfficeDebiId, System.DateTime? OfficeDebitDate, Enumerations.PaymentMethod? PaymentMethod>' 转换为 '(string OfficeDebitId, System.DateTime? OfficeDebitDate, Enumerations.PaymentMethod? PaymentMethod)'

【问题讨论】:

  • 我建议使用元组作为键。
  • @John 你能举个例子吗?谢谢
  • 或使用值元组语法GroupBy(p =&gt; (p.OfficeDebitId, p.OfficeDebitDate, p.PaymentMethod))
  • 这个问题是不是类似stackoverflow.com/questions/61712856/…
  • @PavelAnikhouski 这是另一个问题,无法添加重复的键,这已经解决了

标签: c# linq group-by


【解决方案1】:

您应该使用TuplesAnonymous Types,但不要将它们组合使用。如果你想使用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();

还请注意,我删除了方法 Sum() 的调用,因为字典 groupedDataDictionary 已经包含聚合数据:x.Sum(p =&gt; p.Amount)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-27
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多