I have a List of List of KeyValuePairs which I would like to bring to a standard form and further export it as a table. To do this I need to get all unique Keys present in the list. How can I get the unique keys with LINQ?
My source data has this form:
var sourceData = new List<List<KeyValuePair<string, string>>>();
...
var uniqueKeyNames = sourceData.SomeLinqCodeHere....
Many thanks
It sounds like you just need a combination of SelectMany
, Select
and Distinct
:
var allKeys = sourceData.SelectMany(list => list) // Flatten to a sequence of KVP
.Select(kvp => kvp.Key) // Select just the keys
.Distinct();
Note that if you want to iterate over allKeys
more than once, you probably want to materialize the query, e.g. by calling ToList
at the end:
var allKeys = sourceData.SelectMany(list => list) // Flatten to a sequence of KVP
.Select(kvp => kvp.Key) // Select just the keys
.Distinct()
.ToList();
Try this:
var uniqueKeyNames = sourceData.SelectMany(l => l).Select(kv => kv.Key).Distinct();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With