I am learning C# and needed to merge two dictionaries so I could add values found in both.
The first dictionary is payePlusNssf that holds a value for each key (key represents employee ID). So far I have employees 1,2,3,4 and 5
Dictionary<int, decimal> payePlusNssf = new Dictionary<int, decimal>();
paye.ToList().ForEach(x =>
{
var deductNSSF = x.Value + nssfAmount;
payePlusNssf.Add(x.Key, deductNSSF);
});
The 2nd dictionary is nhifRatesDictionary that holds rates to be added to each value per employee in the first dictionary.
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; }
}
In summary I need this after merging and adding:
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
How do I achieve this? I have looked at past similar problems on this site but have not been very helpful to me.
Not tested but try:
This assumes that since the value of
nhifRatesDictionaryis IEnumreable you want to sum over all the values in the enumerable. This should also work if the IEnumerable is empty. If you know that there is exactly one value for each key then you can use: