简体   繁体   中英

How to get list of keys in a dictionary with group by value with using LinQ

Ok here a simple dictionary

Dictionary<string,int> dicClusters=new Dictionary<string,int>();

dicClusters.Add("A",1);
dicClusters.Add("B",1);
dicClusters.Add("C",2);
dicClusters.Add("D",3);

So i want to compose Lists like below from this

  List<List<string>> lstGroupedByKeys=dicClusters.GroupBy(pr => pr.Value)...

The result will be

first list {"A","B"}
second list {"C"}
third list {"D"}

i can code it with multiple foreach or using for loops however i believe it can be done with linQ and i want to learn ty

c# .NET 4.5.2

GroupBy is the right way to go, but you need another Select to define how each of the groups should be represented:

List<List<string>> lstGroupedByKeys =
    dicClusters.GroupBy(pr => pr.Value)
               .Select(g => g.Select(pr => pr.Key).ToList())
               .ToList();

or you can use different GroupBy overload:

List<List<string>> lstGroupedByKeys =
    dicClusters.GroupBy(pr => pr.Value, pr => pr.Key, (k, g) => g.ToList())
               .ToList();

It might be cleaner when using syntax-based query:

var lstGroupedByKeys = (from pr in dicClusters
                        group pr.Key by pr.Value into g
                        select g.ToList()).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM