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

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

问题描述

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

I'm stumped by this easy data problem.

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

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?

推荐答案

使用 Select 的索引重载:

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天全站免登陆