Home > database >  How to groupping a list<dictionary<string,string>> based on particular key in c#
How to groupping a list<dictionary<string,string>> based on particular key in c#

Time:12-20

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. Can anyone help me on this

I try many ways but didn't get any solution so far

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

CodePudding user response:

You can work with LINQ. Group by HoleName and get the last grouped dictionary item.

using System.Linq;

List<Dictionary<string, string>> result = data.GroupBy(x => x.GetValueOrDefault("HoleName"))
    .Select(g => g.Last())
    .ToList();

Demo @ .NET Fiddle

  • Related