简体   繁体   English

在多个字典中找到每个键的最大值

[英]finding the max of value for each key in multiple dictionaries

I have 3 dictionaries and need to create a new dictionary which should contain the highest number of value for the same key. 我有3个字典,需要创建一个新字典,该字典应包含相同键的最大数量的值。 For example r1 has (10, 100), r2 has (10, 200), r3 has (10, 500). 例如r1具有(10,100),r2具有(10,200),r3具有(10,500)。 The new dictionary should have 10, 500. 新字典应该有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: 未经测试,但想法是:

  • get all the pairs 得到所有的对
  • group them by key 按键分组
  • generate a new pair with the max of each group 生成每个组的最大值的新对
  • convert this set to a dictionary 将此集转换为字典

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM