Home > Back-end >  How to group a list<dictionary<string,string>> based on particular key in c#
How to group a list<dictionary<string,string>> based on particular key in c#

Time:12-21

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

  1. Group by HoleName.

  2. Get the max value via .Max() (Must convert the Length 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

  1. Order by HoleName and followed by Length descending (Must convert the Length to numeric type).

  2. Group by HoleName.

  3. 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;
        }
    }
}
  • Related