如何在linq查询中编写distinct和count?

时间:2013-10-30 16:21:08

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

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

2 个答案:

答案 0 :(得分: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()
                                   }
                         );

答案 1 :(得分: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();