2

I basically want to know how to write this (Extract all keys from a list of dictionaries) in C#.

I have a list of dictionaries which have all unique keys.

I want to extract all of them into a list of string (as the key is string).

private List<Dictionary<string, string>> dictList = new List<Dictionary<string, string>>
{
     new Dictionary<string, string>() { { "a", "b" } },
     new Dictionary<string, string>() { { "c", "d" } },
};

private void GetDictListKeys()
{
    List<string> keyList = new List<string>();
    foreach(var dict in dictList)
    {
        keyList.Add(dict.Keys.ToString());
    }
}

Thank you.

3 Answers3

5

You want to flatten your enumerable of keys and dump it into a collection (HashSet used cause you mentioned duplicates, and because that's also what your linked answer used in Python):

var allKeys = dictList.SelectMany(d => d.Keys).ToHashSet();
Blindy
  • 65,249
  • 10
  • 91
  • 131
2

You can create another foreach loop inside yours:

foreach (Dictionary<string,string> dict in dictList)
{
    foreach(string key in dict.Keys)
    {
        keyList.Add(key);                 
    }
}
josibu
  • 594
  • 1
  • 6
  • 23
MTO
  • 41
  • 5
2

You can use AddRange.

    foreach (var dict in dictList)
    {
        keyList.AddRange(dict.Keys);
    }
thewallrus
  • 645
  • 4
  • 8