繁体   English   中英

如何使用LINQ查找词典列表中每个键的最大值?

[英]How to find the maximum value for each key in a List of Dictionaries using LINQ?

我有一个字典列表,其中包含字符串类型和值为int的键。

许多词典中都有相同的键,但不是全部。

所以我的问题是:使用LINQ如何在所有字典中找到与每个不同键相关联的最大值?

例如,给出以下输入:

var data = new List<Dictionary<string, int>>
{
    new Dictionary<string, int> {{"alpha", 4}, {"gorilla", 2}, {"gamma", 3}},
    new Dictionary<string, int> {{"alpha", 1}, {"beta", 3}, {"gamma", 1}},
    new Dictionary<string, int> {{"monkey", 2}, {"beta", 2}, {"gamma", 2}},
};

我想要某种包含以下内容的集合:

{"alpha", 4},
{"gorilla", 2},
{"gamma", 3},
{"beta", 3},
{"monkey", 2}

(我现在正在遍历列表并自己跟踪事物,真的只是想知道是否有更好的LINQ式方式)

编辑:我也不知道字符串键是什么提前

var results = data.SelectMany(d => d)
                  .GroupBy(d => d.Key)
                  .Select(g => new
{
    GroupName = g.Key,
    MaxValue = g.Max(i => i.Value)
});

并测试以上,使用此

foreach (var item in results)
{
    Console.WriteLine(item);
}

获得以下输出...

{ GroupName = alpha, MaxValue = 4 }
{ GroupName = gorilla, MaxValue = 2 }
{ GroupName = gamma, MaxValue = 3 }
{ GroupName = beta, MaxValue = 3 }
{ GroupName = monkey, MaxValue = 2 }

暂无
暂无

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

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