如何在 linq 查询中编写非重复数和计数

本文关键字:linq 查询 | 更新日期: 2023-09-27 18:37:26

我有一个 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 表达式?

如何在 linq 查询中编写非重复数和计数

       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();

您可以将其分为三个部分:

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()
                                   }
                         );