user610217
user610217

Reputation:

Collect a distinct list of key values from a nested collection?

This seems like it is completely straightforward, but my brain isn't working very well this morning, and I can't seem to find a good search expression for the answer.

I have an IList<IDictionary<string, string>> and I want to get an IList<string> containing a distinct list of unique key names in my collection of dictionary objects. What's a quick and elegant way to do this? I'm sure the answer is simple, I just can't think of it.

Upvotes: 2

Views: 3065

Answers (2)

SLaks
SLaks

Reputation: 888107

list.SelectMany(d => d.Keys).Distinct()

Upvotes: 2

Thomas Levesque
Thomas Levesque

Reputation: 292675

var allKeys = from dict in list
              from key in dict.Keys
              select key;

var distinctKeys = allKeys.Distinct().ToList();

Or if you prefer lambda syntax:

var distinctKeys = list.SelectMany(dict => dict.Keys).Distinct().ToList();

Upvotes: 3

Related Questions