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

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

问题描述

我有一个场景,如果满足特定的布尔值(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天全站免登陆