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.

0

3 Answers 3

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(); 
Sign up to request clarification or add additional context in comments.

2 Comments

If you actually want a list, use ToList() instead.
... or if you want unique keys but a list use dictList.SelectMany(d => d.Keys).Distinct().ToList()
2

You can use AddRange.

 foreach (var dict in dictList) { keyList.AddRange(dict.Keys); } 

1 Comment

Another beautiful way to get what I wanted. Thank you!
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); } } 

1 Comment

Couldn't really think of having two loops! Thank you very much!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.