【问题标题】:get top 5 frequent values and their total count Linq-to-Sql获取前 5 个频繁值及其总数 Linq-to-Sql
【发布时间】:2019-03-25 01:25:44
【问题描述】:

我正在使用这个 Linq to sql 来获取出现最多的记录。

List<int> result;
result = await context.InvoiceItems.GroupBy(q => q.ProductID)
        .OrderByDescending(gp => gp.Count())
        .Take(5)
        .Select(g => g.Key).ToListAsync();  

并获取 int 类型值。但我也想获得每个值出现的总次数。就像这个 SQL 查询正在返回。

select productID, Count(*) AS value_occurrence from InvoiceItems group by productID  

查看这张桌子图片

【问题讨论】:

    标签: c# sql linq-to-sql


    【解决方案1】:

    您需要按ProductID 分组,然后将结果投影到Sample 类中,一个属性为.Key,第二个属性为.Count()

    List<Sample> result = await context.InvoiceItems.GroupBy(q => q.ProductID)
                      .OrderByDescending(gp => gp.Count())
                      .Take(5)
                      .Select(g => new Sample { ProductID = g.Key, Value_Occurence = g.Count() }).ToListAsync();
    
    result.ForEach(x => Console.WriteLine($"ID: {x.ProductID}, \t Value_Occurence: {x.Value_Occurence}"));
    

    您可以将结果投影到下面的示例类中。

    class Sample
    {
        public int ProductID { get; set; }
        public int Value_Occurence { get; set; }
    }
    

    输出:每个productID只输入一个InvoiceItem

    【讨论】:

    • 什么是结果类型而不是 var ?
    • @Hammas_stack1,回答更新,现在结果类型是List&lt;Sample&gt;
    • @Hammas_stack1,更新前result的类型为匿名类型
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    • 2020-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    相关资源
    最近更新 更多