如何添加到ROW_NUMBER LINQ查询或实体? [英] How do I add ROW_NUMBER to a LINQ query or Entity?

查看:298
本文介绍了如何添加到ROW_NUMBER LINQ查询或实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被这个简单的数据问题难住了。

I'm stumped by this easy data problem.

我使用实体框架,并有产品数据库。我的结果页面返回这些产品的分页列表。现在我的结果是由销售每个产品的数量排序,所以我的code是这样的:

I'm using the Entity framework and have a database of products. My results page returns a paginated list of these products. Right now my results are ordered by the number of sales of each product, so my code looks like this:

return Products.OrderByDescending(u => u.Sales.Count());

这将返回我的实体的一个IQueryable数据集,以销售数量来分类的。

This returns an IQueryable dataset of my entities, sorted by the number of sales.

我希望我的结果页面显示每个产品的排名(数据集中)。我的结果应该是这样的:

I want my results page to show the rank of each product (in the dataset). My results should look like this:

Page #1
1. Bananas
2. Apples
3. Coffee

Page #2
4. Cookies
5. Ice Cream
6. Lettuce

我期待,我只是想在使用SQL ROW_NUMBER可变我的结果添加一列...但我不知道如何将此列添加到我的结果数据表。

I'm expecting that I just want to add a column in my results using the SQL ROW_NUMBER variable...but I don't know how to add this column to my results datatable.

我的结果页面中确实包含一个foreach循环,但由于我使用的是一套分页我用这个数字来假一排序号码不会是最好的办法猜测。

My resulting page does contain a foreach loop, but since I'm using a paginated set I'm guessing using that number to fake a ranking number would NOT be the best approach.

所以我的问题是,我怎么一个ROW_NUMBER列在这种情况下,添加到我的查询结果?

So my question is, how do I add a ROW_NUMBER column to my query results in this case?

推荐答案

使用索引超载选择

var start = page * rowsPerPage;
Products.OrderByDescending(u => u.Sales.Count())
    .Skip(start)
    .Take(rowsPerPage)
    .AsEnumerable()
    .Select((u, index) => new { Product = u, Index = index + start });

这篇关于如何添加到ROW_NUMBER LINQ查询或实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆