简体   繁体   English

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

[英]Aggregate function Count() using dynamic linq query

I am trying to use Aggregate function Count() on some column using dynamic linq query but I am not able to achieve, what I am exactly looking is 我正在尝试使用动态linq查询在某些列上使用Aggregate function Count() ,但我无法实现,我正在寻找的是

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

I want to convert the same query to dynamic linq query, any suggestions on how to achieve this? 我想将同一查询转换为动态linq查询,关于如何实现这一点的任何建议?

May be something like this 可能是这样的

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

Stolen from here : 这里被盗:

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

The following two queries will give you the exact same result: first with lambda second result without. 以下两个查询将为您提供完全相同的结果:第一个查询使用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());
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM