0

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

4

2 回答 2

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();
于 2013-10-30T16:39:43.853 回答
1

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

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()
                                   }
                         );
于 2013-10-30T16:33:06.383 回答