简体   繁体   English

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

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

I have a List of Dictionaries that have keys of type string and values that are ints. 我有一个字典列表,其中包含字符串类型和值为int的键。

Many of the dictionaries have the same keys in them but not all of them. 许多词典中都有相同的键,但不是全部。

So my question is: using LINQ how would I find the maximum value associated with each distinct key across all of the dictionaries? 所以我的问题是:使用LINQ如何在所有字典中找到与每个不同键相关联的最大值?

So for example given the following input: 例如,给出以下输入:

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}},
};

I would like some kind of collection that contains: 我想要某种包含以下内容的集合:

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

(I'm currently looping through the list and keeping track of things myself, really just wondering if there is a nicer LINQ-esque way of doing it) (我现在正在遍历列表并自己跟踪事物,真的只是想知道是否有更好的LINQ式方式)

EDIT: I also don't know what the string keys are in advance 编辑:我也不知道字符串键是什么提前

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

and to test the above, use this 并测试以上,使用此

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

to get the following output... 获得以下输出...

{ 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