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?
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.