Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select in LINQ all keys from List of List of KeyValuePairs

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

like image 863
lekso Avatar asked Aug 29 '13 14:08

lekso


2 Answers

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();
like image 122
Jon Skeet Avatar answered Nov 08 '22 19:11

Jon Skeet


Try this:

var uniqueKeyNames = sourceData.SelectMany(l => l).Select(kv => kv.Key).Distinct();
like image 2
ataravati Avatar answered Nov 08 '22 17:11

ataravati