سؤال

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();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top