Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/263.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用LINQ查找字典列表中每个键的最大值?_C#_Linq_C# 3.0 - Fatal编程技术网

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

C# 如何使用LINQ查找字典列表中每个键的最大值?,c#,linq,c#-3.0,C#,Linq,C# 3.0,我有一个字典列表,其中包含字符串类型的键和int值 许多字典都有相同的键,但不是所有的 所以我的问题是:使用LINQ,如何在所有字典中找到与每个不同键关联的最大值 例如,给定以下输入: var data = new List<Dictionary<string, int>> { new Dictionary<string, int> {{"alpha", 4}, {"gorilla", 2}, {"gamma", 3}}, new Dictio

我有一个字典列表,其中包含字符串类型的键和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}},
};
(我目前正在浏览列表,并自己跟踪事情,真的只是想知道是否有一种更好的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 }

了不起的为什么当你看到它时它总是那么明显:-)当然,还有很多其他方法可以做同样的事情:
data.SelectMany(d=>d.GroupBy(d=>d.Key,d=>d.Value,(k,i)=>new{GroupName=k,MaxValue=i.Max()}
从数据中的d.SelectMany(i=>i)将d.Value按d.Key分组到g中,选择新的{GroupName=g.Key,MaxValue=g.Max()}
是其中的两个。
{ GroupName = alpha, MaxValue = 4 }
{ GroupName = gorilla, MaxValue = 2 }
{ GroupName = gamma, MaxValue = 3 }
{ GroupName = beta, MaxValue = 3 }
{ GroupName = monkey, MaxValue = 2 }