0

I have two tables: Category (Id, Name, ...) and Question (Id, CategoryId, Title, ...) with relation Category 1-* Question. I need to get the top three categories (with the highest number of questions) from the database. I wrote this SQL query:

SELECT TOP 3 c.Name, COUNT(q.CategoryId)
FROM Category c
JOIN Question q
ON c.Id = q.CategoryId
GROUP BY Name
ORDER BY COUNT(q.CategoryId) DESC

and of course it works, but I need to write this query in LINQ. The main problem is in the first line with COUNT. How should I use it in this query?

0

1 Answer 1

3

I'm not sure where your data comes from but the query will look something like

var q =
    from c in categories
    join q in questions on c.Id equals q.CategoryID
    group c by c.Name into g 
    orderby g.Count() descending
    select new
    {
        Name = g.Key,
        Count = g.Count()
    };

 q = q.Take(3);
Sign up to request clarification or add additional context in comments.

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.