【问题标题】:How to write distinct and count in a linq query? [closed]如何在 linq 查询中编写 distinct 和 count ? [关闭]
【发布时间】:2013-10-30 16:21:08
【问题描述】:

我有一个 SQL,我正在尝试将其转换为 c# 中的 Linq 表达式。

你能帮忙吗?

if (String.IsNullOrEmpty(alpha))
    sql = "select distinct(Keyword) as word, 
                  count(*) as Counter 
           from Keywords 
           group by keyword 
           order by keyword desc";
else
    sql = "select distinct(Keyword) as word, 
                  count(*) as Counter 
          from Keywords 
          where starts = N'{0}' 
          group by keyword 
          order by keyword desc";

我知道我在同一个查询中有不同的和计数的,没有什么好的方法可以弄清楚如何做到这一点?如何为此编写我的 LinQ 表达式?

【问题讨论】:

    标签: c# .net sql linq linq-to-sql


    【解决方案1】:
           int? startFilter = 10;
    
    
            var test1 = items.Where(i => startFilter.HasValue == false || i.Starts == startFilter.Value)
                             .GroupBy(i => i.Keyword).Select(grp => new { Keyword = grp.Key, Count = grp.Count()})
                             .ToList();
    

    【讨论】:

    • 稍作修改就可以了。谢谢!!
    【解决方案2】:

    你可以把它分成三个部分:

    IEnumerable<Keyword> query = db.Keywords;
    
    if(String.IsNullOrEmpty(alpha))
        query = query.Where(k => k.starts == alpha)
    
    // need to change from Keyword collection to anonymous type collection
    var query2 = query.GroupBy(k => k.Keyword)   
                      .Select(g => new {
                                       word = g.Key,
                                       Counter = g.Count()
                                       }
                             );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-29
      相关资源
      最近更新 更多