C# 合并 2 个字典并在它们之间添加值

标签 c# dictionary

我正在学习 C#,需要合并两个字典,以便我可以添加在两个字典中找到的值。

第一个字典是 payePlusNssf,它保存每个键的值(键代表员工 ID)。到目前为止,我有员工 1、2、3、4 和 5

Dictionary<int, decimal> payePlusNssf = new Dictionary<int, decimal>();

paye.ToList().ForEach(x =>
{
    var deductNSSF = x.Value + nssfAmount;

    payePlusNssf.Add(x.Key, deductNSSF);
});

第二个字典是 nhifRatesDictionary,它保存要添加到第一个字典中每个员工的每个值的费率。

Dictionary<int, IEnumerable<NHIFRates>> nhifRatesDictionary =
   new Dictionary<int, IEnumerable<NHIFRates>>();

basicPayDictionary.ToList().ForEach(x =>
{
    List<NHIFRates> nhifValueList = new List<NHIFRates>();

    // Using Employee basic pay
    decimal basicPay = x.Value;

    bool foundflag = false;

    foreach (var item in nhifBracketList)
    {
        if (basicPay >= item.Min && basicPay <= item.Max)
        {
            nhifValueList.Add(new NHIFRates { Rate = item.Rate });

            foundflag = true;
            break;
        }                       
    }

    if (!foundflag)
    {
        nhifValueList.Add(new NHIFRates { Rate = 0m });
    }

    nhifRatesDictionary.Add(x.Key, nhifValueList);
});

struct NHIFRates
{
    public decimal Rate { get; set; }
}

总之,合并和添加后我需要这个:

Dict 1          Dict 2          Result Dict 3
key  value      key  rate       key  value
1     500       1     80        1    580
2    1000       2     100       2   1100
3    2000       3     220       3   2220
4     800       4     300       4   1100
5    1000       5     100       5   1100

我该如何实现这一目标?我曾经在这个网站上查看过类似的问题,但对我来说没有太大帮助。

最佳答案

尚未测试,但请尝试:

payePlusNssf.ToDictionary(
            v => v.Key, 
            v => v.Value + nhifRatesDictionary[v.Key].Sum(nhifr => nhifr.Rate)
                         );

这假设由于 nhifRatesDictionary 的值是 IEnumreable,因此您想要对可枚举中的所有值求和。如果 IEnumerable 为空,这也应该有效。如果您知道每个键只有一个值,那么您可以使用:

payePlusNssf.ToDictionary(
            v => v.Key, 
            v => v.Value + nhifRatesDictionary[v.Key].Single(nhifr => nhifr.Rate)
                         );

关于C# 合并 2 个字典并在它们之间添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7631883/

相关文章:

c# - 如何读取带图片的word文件

c# - 字典方法 Remove 和 Clear (.NET Core) 在枚举期间修改集合。没有抛出异常

python - 如何合并具有重复键的字典列表

arrays - 尝试将值附加到字典中的数组

c# - 在来自同一 MySQL 服务器的不同数据库的两个表中执行连接查询

c# - 将 C# List<T> 一分为二

c# - 我如何使用条件运算符编写多条语句

c# - 使用 MySQL 代替 LocalDb

python - 为什么其他列表也发生变化?

python - 替换Python字典中的文本