.net 如何根据特定键对List〈Dictionary〈string,string>>进行分组并获取最大值

c9x0cxw0  于 2022-12-24  发布在  .NET
关注(0)|答案(2)|浏览(329)

我有下面的List<Dictionary<string,string>>

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。我尝试了很多方法,但到目前为止还没有得到任何解决方案。
预期产出:

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" }
};
qltillow

qltillow1#

您可以使用LINQ。Group by HoleName and获取字典的最大Length(随着问题的更新)。

方法1

1.按HoleName分组。
1.通过.Max()获取最大值(在获取最大值之前,必须将Length转换为数值类型)。

using System.Linq;

List<Dictionary<string, string>> result = data.GroupBy(x => x.GetValueOrDefault("HoleName"))
    .Select(g => new Dictionary<string, string>
    {
        ["HoleName"] = g.Key,
        ["Length"] = g.Max(x => int.Parse(x.GetValueOrDefault("Length"))).ToString()
    })
    .ToList();

方法2

1.按HoleName排序,后跟Length降序(必须将Length转换为数值类型)。
1.按HoleName分组。
1.通过.First()获取每组的第一个项目。

using System.Linq;

List<Dictionary<string, string>> result = data
    .OrderBy(x => x.GetValueOrDefault("HoleName")!)
    .ThenByDescending(x => int.Parse(x.GetValueOrDefault("Length")!))
    .GroupBy(x => x.GetValueOrDefault("HoleName")!)
    .Select(g => g.First())
    .ToList();

n6lpvg4x

n6lpvg4x2#

var dicHoleName = new Dictionary<string, string>();

foreach (var dic in data)
{
    foreach (var kv in dic)
    {
        if (kv.Key == "HoleName")
        {
            dicHoleName[kv.Key] = kv.Value;
        }
    }
}

相关问题