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.
CodePudding user response:
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();
CodePudding user response:
You can create another foreach loop inside yours:
foreach (Dictionary<string,string> dict in dictList)
{
foreach(string key in dict.Keys)
{
keyList.Add(key);
}
}
CodePudding user response:
You can use AddRange.
foreach (var dict in dictList)
{
keyList.AddRange(dict.Keys);
}