获取前五个最常见的值及它们的总数(Linq-to-Sql)。

3
我正在使用 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  

请看下面的表格图片:

SQL results

1个回答

2
你需要按照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; }
}

输出:每个产品ID只有一个InvoiceItem的输入。

enter image description here


在 var 的位置,结果的类型将是什么? - Hammas_Stack1
@Hammas_stack1,回答已更新,现在结果的类型是List<Sample> - er-sho
@Hammas_stack1,在更新result的类型之前,它是一个匿名类型。 - er-sho

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接