【问题标题】:How to get list of keys in a dictionary with group by value with using LinQ如何使用 LinQ 按值分组获取字典中的键列表
【发布时间】:2015-09-06 21:44:35
【问题描述】:

好的,这里有一个简单的字典

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

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

所以我想由此组成如下列表

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

结果是

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

我可以使用多个 foreach 或使用 for 循环对其进行编码,但是我相信它可以使用 linQ 来完成,我想学习 ty

c#.NET 4.5.2

【问题讨论】:

    标签: c# linq dictionary group-by


    【解决方案1】:

    GroupBy 是正确的方法,但您需要另一个 Select 来定义每个组的表示方式:

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

    或者你可以使用不同的GroupBy重载:

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

    使用基于语法的查询可能会更简洁:

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

    【讨论】:

    • 效果很好。我尝试使用 group by 但我无法完成它:D 我也更喜欢第一个解决方案,因为它对我更有意义
    • 你能解释一下这个重载的东西吗,它看起来真的很好。它是如何工作的?
    • 在 msdn 上有很好的描述:msdn.microsoft.com/en-us/library/vstudio/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    • 2022-12-05
    • 1970-01-01
    相关资源
    最近更新 更多