简体   繁体   English

如何使用TOP,COUNT和GROUP BY转换SQL语句以使用LINQ返回对象列表

[英]How to convert SQL Statement with TOP, COUNT and GROUP BY to return an object list with LINQ

does anyone know how to convert this SQL statement to a LINQ to a List? 有谁知道如何将此SQL语句转换为LINQ到列表?

SELECT TOP(5) COUNT(Tickets.CategoryId), Categories.CategoryName
FROM Tickets 
INNER JOIN Categories ON Tickets.CategoryId = Categories.CategoryId
GROUP BY Categories.CategoryName
ORDER BY 1 DESC

The result would be something like this? 结果将是这样吗?

public static List<Categories> List()
{
    MyEntities db = new MyEntities();

    var categories = (from ticket in db.Ticket.Include("Category")
                        group ticket by ticket.Category.CategoryId into g
                        orderby g.Count() descending
                        select g.FirstOrDefault().Category).Take(5).ToList();

    return categories;

}

Have you tried creating a view from your query and calling that from Linq? 您是否尝试过通过查询创建视图并从Linq调用视图? It would look to Linq like a table. 在Linq看来,它就像一张桌子。 You could use the exact query you provided above. 您可以使用上面提供的确切查询。

You may be looking for a Linq only answer, but using a view would be a quick way to get there and you may get a slight boost in performance if you are hitting it very frequently. 您可能正在寻找仅Linq的答案,但是使用视图是到达那里的快速方法,并且如果您经常点击它,性能可能会有所提高。

I like to use DB for the things it is good at, and it looks to me like this might just be a good fit. 我喜欢将DB用于它擅长的事情,在我看来,这可能是一个很好的选择。

If you go with a Linq only solution, you might want to spend a few minutes trying the view and doing timing tests to see if it makes a difference in your app. 如果使用仅支持Linq的解决方案,则可能需要花几分钟时间尝试查看视图并进行时序测试,以查看它是否对您的应用有所帮助。

Looks like you just need to change the "SELECT" portion of your statement: 看起来您只需要更改语句的“ SELECT”部分:

select new { Count = g.Count(), 
    CategoryName = g.FirstOrDefault().Category.CategoryName }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM