I have a dictionary that map between certain keys
var map = new Dictionary<string, string>(){ {"A", "One"}, {"B", "One"}, {"C", "Two"} };
I also have a dictionary containing values
var values = new Dictionary<string, double>() { {"A", 2.0}, {"B", 1.0}, {"C", 1.0} };
I want to map the values into a third dictionary so that the value of map
is the key of the new dictionary. I.e. I want the new dictionary to be
var result = new Dictionary<string, double>() {{"One", 3.0}, {"Two", 1.0}};
This can of course be achieved using loops like so
var result = new Dictionary<string, double>();
foreach (var kv in values)
{
var key = map[kv.Key];
var value = kv.Value;
if (result.TryGetValue(key, out var temp))
result[key] = value temp;
else
result.Add(key, value);
}
Or something like that...
But is it possible to do this in a one-liner using linq?
CodePudding user response:
Try this,
var result = map
.Join(values, x => x.Key, y => y.Key, (x, y) => (x.Value, y.Value))
.GroupBy(x => x.Item1)
.ToDictionary(x => x.Key, y => y.Sum(s => s.Item2));
DotNet Fiddle: https://dotnetfiddle.net/tWd9j5
CodePudding user response:
Looks like you're looking for Join method
var result = map.Join(values, x => x.Key, y => y.Key, (x, y) => (x.Value, y.Value)).ToDictionary(x => x.Item1, y => y.Item2);
And to handle duplication of value
var result = map
.Join(values, x => x.Key, y => y.Key, (x, y) => (x.Value, y.Value))
.GroupBy(x => x.Item1)
.ToDictionary(x => x.Key, y => y.First().Item2);
CodePudding user response:
Sure you can.
var result = (from m in map
join v in values
on m.Key equals v.Key
group v.Value by m.Value into sameVal
select new { MValue = sameVal.Key, VValue = sameVal.Sum() }).ToDictionary(a => a.MValue, b => b.VValue);