使用动态 linq 查询的聚合函数 Count()

本文关键字:函数 Count 动态 linq 查询 | 更新日期: 2023-09-27 18:32:48

我正在尝试使用动态linq查询对某些列使用Aggregate function Count(),但我无法实现,我正在寻找的是

Select Count(Id),Id 
from Table1 
Group By Id 
Having Count(Id) > 1

我想将相同的查询转换为动态 linq 查询,关于如何实现这一点的任何建议?

使用动态 linq 查询的聚合函数 Count()

从这里偷来的:

var distinctItems = 
    from list in itemsList
    group list by list.ItemCode into grouped
    where grouped.Count() > 1
    select grouped;

以下两个查询将给出完全相同的结果:第一个与 lambda 第二个结果没有。

        var Table1 = new List<Row>();
        for (int i = 0; i < 10; i++)
        {
            for (int m = 0; m < 5; m++)
            {
                for (int x = 0; x < i + m; x++)
                {
                    Table1.Add(new Row() { Id = m });
                }
            }
        }
        var result = Table1.GroupBy(row => row.Id)
                    .Where(p => p.Count() > 1);
        var resultB = from row in Table1
                      group row by row.Id into rowGrouped
                      where rowGrouped.Count() > 1
                      select rowGrouped;
        foreach (var r in resultB)
        {
            Console.WriteLine("ID {0} count: {1}", r.Key, r.Count());
        }
可能是

这样的

list.GroupBy(item => item.Id)
    .Where(group => group.Count() > 1)
    .Select(group => new {
                         Id = group.Key, 
                         Count = group.Count() });