【问题标题】:Converting SQL to Linq query将 SQL 转换为 Linq 查询
【发布时间】:2017-02-23 21:30:32
【问题描述】:

我正在尝试将以下查询的输出转换为 Linq 查询

SELECT SearchQueries.Query,
       Clicks.Name,
       COUNT (SearchQueries.Query) AS Hits
FROM SearchQueries
INNER JOIN Clicks ON Clicks.SearchqueryId = SearchQueries.Id
GROUP BY SearchQueries.Query, Clicks.Name
ORDER BY Hits DESC

但我似乎无法弄清楚如何做到这一点; 这就是我目前所拥有的

var result =
    _db.Clicks.Select(q => q)
        .GroupBy(q => q.Name, g => g.Searchquery.Query)
        .ToDictionary(g=> g.Key, g => g);

但我将如何继续?

结果是这样的:

+---------------+-------------------+------+
|Query          | Name              | Hits |
+---------------+-------------------+------+
|tag            | dnfsklmfnsd       | 53   |
|tag2           | dgsqfsdf          | 17   |
+---------------+-------------------+------+

原始表格如下所示

搜索查询

+---+-------+
|Id | Query |
+---+-------+
| 1 | tag   | x 53
| 2 | tag2  | x 17
+---+-------+

点击次数

+---+-------------------+---------------+
|Id | Name              | SearchqueryId |
+---+-------------------+---------------+
| 1 | dnfsklmfnsd       | 1             |
| 2 | dgsqfsdf          | 2             |
+---+-------------------+---------------+

【问题讨论】:

标签: c# sql linq sql-to-linq-conversion


【解决方案1】:

尝试使用GroupByCount:(我将顺序更改为在表达式中使用SearchQueries作为“基表”,只是为了更容易与SQL语句进行比较)

var result =
    _db.SearchQueries
       .GroupBy(sq => new { name = sq.Clicks.Name, query = sq.Query)
       .Select(sq => new {
                           Query = sq.Query,
                           Name = sq.Clicks.Name,
                           Hits = sq.Count()
                         })
       .OrderByDescending(sq => sq.Hits);

【讨论】:

  • 您好,谢谢!另一个问题:当我添加 .Where(g => !string.Equals(g.Key.query, g.Key.name, StringComparison.CurrentCultureIgnoreCase)) 时,它打破了查询:/
  • @Kiwi 有什么错误?属性name一定要大写对吗?
  • 显然有一些东西不能使用 string.equals 将其更改为 g.Key.query != q.Key.name 修复它
【解决方案2】:

好吧,如果您在 Click 上有一个导航属性 Searchquery,就像看起来的那样,您可以这样做

var result =
    _db.Clicks
        .GroupBy(m => new {name = m.Name, query = m.Searchquery.Query)
        .Select(g => new {
           Query = g.Key.query,
           Name = g.Key.name,
           Hits = g.Count()
});

【讨论】:

    猜你喜欢
    • 2014-08-14
    • 1970-01-01
    • 1970-01-01
    • 2012-02-17
    • 2020-07-19
    • 1970-01-01
    • 2016-03-08
    相关资源
    最近更新 更多