【问题标题】:Select most frequent value using LINQ使用 LINQ 选择最常见的值
【发布时间】:2011-10-07 12:59:35
【问题描述】:

我正在尝试选择表中最常见的五个值并将它们返回到一个列表中。

    var mostFollowedQuestions = (from q in context.UserIsFollowingQuestion
                                 select *top five occuring values from q.QuestionId*).toList();

有什么想法吗?

谢谢

【问题讨论】:

    标签: c# sql linq entity-framework


    【解决方案1】:
    var mostFollowedQuestions = context.UserIsFollowingQuestion
                                        .GroupBy(q => q.QuestionId)
                                        .OrderByDescending(gp => gp.Count())
                                        .Take(5)
                                        .Select(g => g.Key).ToList();
    

    【讨论】:

    • @wardh 我想你会发现这实际上给了你最少经常出现的值。我的回答略有不同,但会根据要求给出最频繁发生的情况。
    • 已编辑以提供最频繁的 - 将 Orderby 更改为 OrderbyDescending
    【解决方案2】:
     int[] nums = new[] { 1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7 };
    
     IEnumerable<int> top5 = nums
                .GroupBy(i => i)
                .OrderByDescending(g => g.Count())
                .Take(5)
                .Select(g => g.Key);
    

    【讨论】:

      猜你喜欢
      • 2011-08-25
      • 2018-01-23
      • 1970-01-01
      • 2023-03-29
      • 2013-02-19
      • 2017-01-22
      相关资源
      最近更新 更多