LINQ:添加ROWNUMBER列 [英] LINQ: Add RowNumber Column

查看:103
本文介绍了LINQ:添加ROWNUMBER列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何查询下面被修改,以包括行数(即:结果中的一个基于索引)的柱

How can the query below be modified to include a column for row number (ie: one-based index of results)?

var myResult = from currRow in someTable
               where currRow.someCategory == someCategoryValue
               orderby currRow.createdDate descending
               select currRow;



EDIT1:我正在寻找的结果是 {IDX,COL1 ,COL2 ... COL-N} 不是 {IDX,排}

EDIT2:行数应与结果行不表行

The row number should correspond to result rows not the table rows.

EDIT3:我的DataBind 这些结果到 GridView控件。我的目标是行号列添加到 GridView控件。也许不同的方法会更好。

I DataBind these results to a GridView. My goal was to add a row number column to the GridView. Perhaps a different approach would be better.

推荐答案

使用该方法,语法,其中的 Enumerable.Select 与索引过载:

Use the method-syntax where Enumerable.Select has an overload with the index:

var myResult = someTable.Select((r, i) => new { Row = r, Index = i })
    .Where(x => x.Row.someCategory == someCategoryValue)
    .OrderByDescending(x => x.Row.createdDate);

请注意,这种方法假定你想要的行的原始索引表中,而不是在过滤的结果,因为我选择索引之前,我带过滤器的其中,

Note that this approach presumes that you want the original index of the row in the table and not in the filtered result since i select the index before i filter with Where.

编辑:我正在寻找的结果是{IDX,COL1,COL2 ... COL-N}不是
{IDX,排}。该行号应与结果行没有
表行。

I'm looking for the results to be {idx, col1, col2...col-n} not {idx, row}. The row number should correspond to result rows not the table rows.

然后选择匿名类型,你需要所有列

Then select the anonymous type with all columns you need:

var myResult = someTable.Where(r => r.someCategory == someCategoryValue)
        .OrderByDescending(r => r.createdDate)
        .Select((r, i) => new { idx = i, col1 = r.col1, col2 = r.col2, ...col-n = r.ColN });

这篇关于LINQ:添加ROWNUMBER列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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