I have 3 dictionaries and need to create a new dictionary which should contain the highest number of value for the same key. For example r1 has (10, 100), r2 has (10, 200), r3 has (10, 500). The new dictionary should have 10, 500.
public Dictionary<Double, Double> r1 = new Dictionary<Double, Double>();
public Dictionary<Double, Double> r2 = new Dictionary<Double, Double>();
public Dictionary<Double, Double> r3 = new Dictionary<Double, Double>();
new[] { r1, r2, r3 }.SelectMany(p => p).GroupBy(p => p.Key)
.ToDictionary(g => g.Key, g => g.Max(p => p.Value));
Edit:
class Program
{
static void Main()
{
var r1 = new Dictionary<double, double> { { 10, 200 } };
var r2 = new Dictionary<double, double> { { 10, 300 } };
var r3 = new Dictionary<double, double> { { 10, 500 } };
var r = Merge(r1, r2, r3);
foreach (var p in r)
Console.WriteLine("{0}: {1}", p.Key, p.Value);
}
static IDictionary<double, double> Merge(params Dictionary<double, double>[] dicts)
{
return dicts.SelectMany(p => p).ToLookup(p => p.Key, p => p.Value).ToDictionary(p => p.Key, p => p.Max());
}
}
Maybe something like this:
r1.Concat(r2).Concat(r3)
.GroupBy(p => p.Key)
.Select(g => new KeyValuePair<double, double>(g.Key, g.Max(p => p.Value)))
.ToDictionary(p => p.Key, p => p.Value);
Not tested but the idea is:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.