我有一个字典列表,其中包含字符串类型和值为int的键.
许多词典中都有相同的键,但不是全部.
所以我的问题是:使用LINQ如何在所有字典中找到与每个不同键相关联的最大值?
例如,给出以下输入:
- var data = new List<Dictionary<string,int>>
- {
- new Dictionary<string,int> {{"alpha",4},{"gorilla",2},{"gamma",3}},new Dictionary<string,1},{"beta",3},1}},int> {{"monkey",2}},};
我想要某种包含以下内容的集合:
- {"alpha",{"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 }