我有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>();
答案 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);
未经测试,但想法是: