C#join dictionaries,附加信息

时间:2017-10-31 10:24:40

标签: c# dictionary join

我加入简单的词典没有问题,这段代码运行正常:

        Dictionary<string, KeyValuePair<int, string>> lala01 = new Dictionary<string, KeyValuePair<int, string>>();
        lala01.Add("A", new KeyValuePair<int, string>(5, "lala01"));
        lala01.Add("B", new KeyValuePair<int, string>(2, "lala01"));
        lala01.Add("C", new KeyValuePair<int, string>(8, "lala01"));

        Dictionary<string, KeyValuePair<int, string>> lala02 = new Dictionary<string, KeyValuePair<int, string>>();
        lala02.Add("A", new KeyValuePair<int, string>(1, "lala02"));
        lala02.Add("B", new KeyValuePair<int, string>(9, "lala02"));
        lala02.Add("X", new KeyValuePair<int, string>(4, "lala02"));

        Dictionary<string, KeyValuePair<int, string>> lala03 = new Dictionary<string, KeyValuePair<int, string>>();
        lala03.Add("A", new KeyValuePair<int, string>(7, "lala03"));
        lala03.Add("C", new KeyValuePair<int, string>(4, "lala03"));
        lala03.Add("X", new KeyValuePair<int, string>(1, "lala03"));
        lala03.Add("Q", new KeyValuePair<int, string>(2, "lala03"));

        List<Dictionary<string, KeyValuePair<int, string>>> dictionaries = new List<Dictionary<string, KeyValuePair<int, string>>>();
        dictionaries.Add(lala01);
        dictionaries.Add(lala02);
        dictionaries.Add(lala03);

但现在我想添加更多信息......一个字符串,说明值来自哪个字典。

设置:

        var result = dictionaries.SelectMany(dict => dict)
                     .ToLookup(pair => pair.Key, pair => pair.Value);
                     //Basically I am clueless here  .ToDictionary(group => group.Key, group => group.Select(x => x).Max(x => x.Key)); 

现在要得到结果,这就是它变得有趣的地方:

.list-content

我应该编码什么才能只包含带有最大整数的keyvaluepair?

1 个答案:

答案 0 :(得分:1)

如果你只需要最大值对,你可能正在寻找类似MaxBy的东西(来自MoreLinq)。

 var result = dictionaries.SelectMany(dict => dict)
              .ToLookup(pair => pair.Key, pair => pair.Value)
              .ToDictionary(group => group.Key, group => group.MaxBy(v=> v.Key));

如果您无法使用更多linq,则可以使用OrderBy

进行First
 var result = dictionaries.SelectMany(dict => dict)
              .ToLookup(pair => pair.Key, pair => pair.Value)
              .ToDictionary(group => group.Key, group => group.OrderByDescending(v=> v.Key).First());