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

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

问题描述

我被这个简单的数据问题所困扰。



我正在使用Entity框架并拥有产品数据库。我的结果页面返回这些产品的分页列表。现在我的结果按每个产品的销售数量排序,所以我的代码如下所示:

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

这将返回我的实体的IQueryable数据集,按销售数量排序。



我希望我的结果页面显示每个产品的排名(在数据集中)。我的结果应该如下所示:

 第1页
1.香蕉
2.苹果
3.咖啡

第2页
4.饼干
5.冰淇淋
6.生菜
/ pre>

我希望我只想使用SQL ROW_NUMBER变量在我的结果中添加一列,但我不知道如何添加列到我的结果datatable。



我的结果页面包含一个foreach循环,但是由于我使用一个分页集,我猜想使用该数字来伪造排名数字不会是最好的方法。



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

解决方案

使用索引超负荷选择

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


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());

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

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.

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.

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

解决方案

Use the indexed overload of 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天全站免登陆