2

I'm trying to get the output of the following query into a Linq query

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

But I can't seem to figure out how to do this; this is what I have so far

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

but how would I continue?

the result is something like this:

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

The original tables looks like following

SearchQueries;

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

Clicks;

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

2 Answers 2

1

Try to use GroupBy and Count: (I changed the order to using SearchQueries as "base table" in the expression, just to make it more easy to compare to the SQL-statement)

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Hi, thanks! one additional question: when I added .Where(g => !string.Equals(g.Key.query, g.Key.name, StringComparison.CurrentCultureIgnoreCase)) it broke the query :/
@Kiwi what's the error? Is it correct that the property name must be capitalized?
Apparently there was something not working with the string.equals changing it to g.Key.query != q.Key.name fixed it
0

Well, if you have a navigation property Searchquery on Click, as it looks like, you can do

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.