You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按指定键分组List<Dictionary<string,string>>并获取最大值

按HoleName分组并获取每组最大Length的解决方案

给定如下C#数据:

List<Dictionary<string,string>> data = new List<Dictionary<string,string>> 
{
    new Dictionary<string,string> { ["HoleName"] = "first", ["Length"] = "20" },
    new Dictionary<string,string> { ["HoleName"] = "second", ["Length"] = "40" },
    new Dictionary<string,string> { ["HoleName"] = "first", ["Length"] = "30" }
};

需要按HoleName字段分组,并提取每组中Length的最大值,最终得到目标格式的列表。

解决方案

利用LINQ实现分组与聚合,注意必须将Length字符串转换为数值类型后再比较大小(避免字符串字典序比较导致的错误,比如"100"作为字符串会被判定为小于"90"):

.NET 6+版本(使用MaxBy简化代码)

var result = data
    .GroupBy(d => d["HoleName"])
    .Select(g => 
        new Dictionary<string, string> 
        {
            ["HoleName"] = g.Key,
            ["Length"] = g.MaxBy(d => int.Parse(d["Length"]))["Length"]
        })
    .ToList();

.NET 6以下版本(使用排序替代MaxBy)

var result = data
    .GroupBy(d => d["HoleName"])
    .Select(g => 
        new Dictionary<string, string> 
        {
            ["HoleName"] = g.Key,
            ["Length"] = g.OrderByDescending(d => int.Parse(d["Length"])).First()["Length"]
        })
    .ToList();

最终输出结果

执行上述代码后,result即为目标格式的列表:

List<Dictionary<string,string>> data = new List<Dictionary<string,string>> 
{ 
    new Dictionary<string,string> { ["HoleName"] = "first", ["Length"] = "30" }, 
    new Dictionary<string,string> { ["HoleName"] = "second", ["Length"] = "40" }
};

内容的提问来源于stack exchange,提问作者krishna porwal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 16:25:09