I have the following 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",}};
I want to grouping the above List by HoleName. I tried many ways, but didn't get any solution so far.
CodePudding user response:
You can work with LINQ. Group by HoleName
and get the max Length
value of the dictionary (as the question is updated).
Approach 1
Group by
HoleName
.Get the max value via
.Max()
(Must convert theLength
to numeric type before getting the max).
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();
Approach 2
Order by
HoleName
and followed byLength
descending (Must convert theLength
to numeric type).Group by
HoleName
.Get the first item from each group via
.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();
CodePudding user response:
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;
}
}
}