【问题标题】:Linq Query for Top 10 with Group BY [duplicate]使用 Group BY 查询前 10 名的 Linq [重复]
【发布时间】:2012-06-26 23:04:35
【问题描述】:

可能重复:
Linq - Top value form each group

我有以下结构的数据:

 var lookupDictionary = new Dictionary<string, Dictionary<string, double>>();

我正在尝试编写一个 Linq 查询,通过对内部字典中的双精度值进行求和并降序排列,为我提供外部字典中的前 10 个键。我对 SQL 中的 group by 有很好的了解,但很难将其转换为 Linq。

任何可以演示此类查询的 Linq 专家?

【问题讨论】:

标签: c# linq


【解决方案1】:

你需要分组吗?

var top = lookupDictionary
    .Select(dict => new { dict.Key, InnerCount = dict.Value.Values.Sum() })
    .OrderByDescending(dict => dict.InnerCount)
    .Take(10);

【讨论】:

    【解决方案2】:
    Dictionary<string, Dictionary<string, double>> lookupDictionary = new Dictionary<string, Dictionary<string, double>>();
    lookupDictionary.Select(outerKeyPair => new
    {
        Key = outerKeyPair.Key,
        Sum = outerKeyPair.Value.Values.Sum()
    })
    .OrderByDescending(pair => pair.Sum)
    .Take(10);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-08
      • 1970-01-01
      • 2018-07-20
      • 1970-01-01
      相关资源
      最近更新 更多