【问题标题】:Aggregate function Count() using dynamic linq query使用动态 linq 查询聚合函数 Count()
【发布时间】:2013-09-25 11:37:53
【问题描述】:

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

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

我想将相同的查询转换为动态 linq 查询,有什么建议可以实现吗?

【问题讨论】:

  • 使用具有值Count(ID)的let关键字,然后构造linq查询
  • stackoverflow 部分成为 sql to linq 翻译器
  • 终于解决了。从帖子stackoverflow.com/questions/2531679/… 得到解决方案
  • 您可能想在此处发布您的解决方案,并将其标记为选择的答案,以供其他搜索做同样事情的人使用。

标签: c# sql linq linq-to-entities dynamic-linq


【解决方案1】:

可能是这样的

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

【讨论】:

  • 我想要使用 DynamicLinq 查询的解决方案。您所建议的是使用常规 Linq 查询。
【解决方案2】:

盗自here:

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

【讨论】:

    【解决方案3】:

    以下两个查询将为您提供完全相同的结果: 第一个有 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());
            }
    

    【讨论】:

      猜你喜欢
      • 2011-10-27
      • 1970-01-01
      • 2015-06-18
      • 1970-01-01
      • 1970-01-01
      • 2014-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多