字典分组和总和原因已添加具有相同键的项 [英] Dictionary groupings and sum causes An item with the same key has already been added

查看:363
本文介绍了字典分组和总和原因已添加具有相同键的项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,如果满足特定的布尔值( office_debit_total 行),我可以直接从列中获取金额,否则我需要通过分组来计算一些特定的值,下面是代码:

I have a scenario where in case there is a specific boolean value satisfied (office_debit_total line) I can get amount directly from a column otherwise I need to calculate it by grouping some specific values, here's the code:

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 = p.OfficeEnum == SomeEnum.ValueType ? p.OfficeAmount.ToString() : totalAmounts[p.OfficeDebitId].ToString(),
    payment_method = p.PaymentMethod.Value.ToString(),
}).ToList();

有可能看到 office_debit_total 是根据枚举值计算得出的值,这是我用来获取分组数据的字典:

As it's possible to be seen office_debit_total is calculated depending on enum value, and here's dictionary that I'm using to get grouped data:

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 => x.Sum(p => p.Amount)); 

但是我收到以下错误消息:

But I have receiving following error message:

已经添加了具有相同键的项目。

An item with the same key has already been added.

我尝试写 .ToLookup 而不是 .ToDictionary ,但这对我没有帮助。

I've tried writing .ToLookup instead of .ToDictionary but that didn't helped me..

谢谢大家

欢呼

推荐答案

如果您的词典仅具有 OfficeDebitId 作为密钥,然后您只需要按其分组:

If your dictionary has only OfficeDebitId as key then you need to group by only by it:

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

或使用完整的匿名对象作为键:

or use full anonymous object as key:

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

或以值元组为键:

var totalAmounts = 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));

这篇关于字典分组和总和原因已添加具有相同键的项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆