In LINQ, select all keys from the KeyValuePairs list.

I have a list from the KeyValuePairs list, which I would like to bring to the standard form and further export as a table. To do this, I need to get all the unique Keys that are in the list. How can I get unique keys with LINQ?

My source data has the following form:

var sourceData = new List<List<KeyValuePair<string, string>>>(); ... var uniqueKeyNames = sourceData.SomeLinqCodeHere.... 

Many thanks

+4
source share
2 answers

Looks 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 allKeys over allKeys more than once, you probably want to materialize the query, for example. 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(); 
+13
source

Try the following:

 var uniqueKeyNames = sourceData.SelectMany(l => l).Select(kv => kv.Key).Distinct(); 
+2
source

Source: https://habr.com/ru/post/1499640/


All Articles