Hi i develop web app with c#. I have sql query and i convert to linq but it’s not working true because of order by
My sql query
Select TOP 3 HastalikIsmi From Hastaliklar group by HastalikIsmi order by Count(*) desc
My linq
public List<HastalikDto> GetHastalikDto() { using (SirketDBContext context = new SirketDBContext()) { var result = from hastalik in context.Hastaliklar group hastalik by hastalik.HastalikIsmi into isim select new HastalikDto { HastalikIsmi = isim.Key }; return result.OrderBy(h => h.HastalikIsmi).Take(3).ToList(); } }
Advertisement
Answer
Here’s how you can do the order by on the count of each group and take the 3 with the highest count.
var result = context.Hastaliklar .GroupBy(x => x.HastalikIsmi) .OrderByDescending(grp => grp.Count()) .Select(grp => grp.Key) .Take(3) .ToList();