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

时间:2014-08-12 21:45:39

标签: c# dictionary

我有3个词典,需要创建一个新词典,该词典应该包含同一个键​​的最大值。例如,r1具有(10,100),r2具有(10,200),r3具有(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>(); 

2 个答案:

答案 0 :(得分:2)

new[] { r1, r2, r3 }.SelectMany(p => p).GroupBy(p => p.Key)
                    .ToDictionary(g => g.Key, g => g.Max(p => p.Value));

编辑:

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());
    }
}

答案 1 :(得分:1)

也许是这样的:

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);

未经测试,但想法是:

  • 获得所有对
  • 按键分组
  • 生成一个具有每组最大值的新对
  • 将此套装转换为字典