LINQ:添加RowNumber列

Ste*_*ven 23 .net c# linq

如何修改下面的查询以包括行号列(即:基于一个结果的索引)?

var myResult = from currRow in someTable
               where currRow.someCategory == someCategoryValue
               orderby currRow.createdDate descending
               select currRow;
Run Code Online (Sandbox Code Playgroud)

编辑1:我正在寻找结果{idx, col1, col2...col-n}不是{idx, row}.

EDIT2:行号应对应于结果行而不是表行.

EDIT3:我把DataBind这些结果发给了一个GridView.我的目标是在行中添加一个行号列GridView.也许一种不同的方法会更好.

Tim*_*ter 33

使用方法 - 语法,其中Enumerable.Select包含索引的重载:

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

请注意,此方法假设您需要表中行的原始索引而不是筛选结果,因为我在筛选之前选择了索引Where.

编辑:我正在寻找{idx,col1,col2 ... col-n}而不是{idx,row}的结果.行号应对应于结果行而不是表行.

然后选择包含所需列的匿名类型:

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 });
Run Code Online (Sandbox Code Playgroud)


slo*_*oth 6

使用此Select方法:

通过合并元素的索引,将序列的每个元素投影到新的形式中.

例:

var myResult = someTable.Where(currRow => currRow.someCategory == someCategoryValue)
                        .OrderByDescending(currRow => currRow.createdDate)
                        .Select((currRow, index) => new {Row = currRow, Index = index + 1});
Run Code Online (Sandbox Code Playgroud)

为了回应您的编辑:

如果你想要一个DataTable结果,你可以通过简单地使用一个非Linq方式,DataView然后添加一个额外的列.

someTable.DefaultView.RowFilter = String.Format("someCategory = '{0}'", someCategoryValue);
someTable.DefaultView.Sort = "createdDate";
var resultTable = someTable.DefaultView.ToTable();
resultTable.Columns.Add("Number", typeof(int));
int i = 0;
foreach (DataRow row in resultTable.Rows)
    row["Number"] = ++i;
Run Code Online (Sandbox Code Playgroud)