C# 如何根据索引/行号从数据表中选择行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12930840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:58:47  来源:igfitidea点击:

How to select rows from DataTable based on Index / Row Number?

c#linqdatatableindexingcriteria

提问by Furqan Safdar

I have a DataTable. I want to select the rows based on the Index/Row Numberof the rows in DataTable.

我有一个DataTable. 我想选择基于该行Index/Row Number在行的DataTable

Suppose below is the DataTable:

假设下面是DataTable

----------------    ---------------
| ID   | Name  |    | Index/RowNo |
----------------    ---------------
| A001 | John  |    |      1      |
| A002 | Foo   |    |      2      |
| A003 | Rambo |    |      3      |
| A004 | Andy  |    |      4      |
| ...  | ...   |    |      5      |
----------------    ---------------

Now, i want to select the Rows from above shown DataTableusing criteria say for example Index > 2, In that case First entry at Index 1, A001 | John, will not become part of the resultant DataTable. How can i do it efficiently?

现在,我想DataTable使用标准从上面显示的行中选择,例如Index > 2,在这种情况下,索引 1 处的第一个条目A001 | John将不会成为结果的一部分DataTable。我怎样才能有效地做到这一点?

Moreover, i want to have my result both in the form of DataTableand Linqquery outcome.

此外,我希望有我的结果无论是在形式DataTableLinq查询结果。

I am trying to do something like this:

我正在尝试做这样的事情:

var result = dt.Select("RowNum > 1", "");

OR

或者

var result = from row in dt.AsEnumerable()
             where RowNum > 1
             select row;

采纳答案by cuongle

var result = table.AsEnumerable()
                  .Where((row, index) => index > 1)
                  .CopyToDataTable()

回答by Tim Schmelter

I am trying to do something like this:

var result = dt.Select("RowNum > 1", "");

我正在尝试做这样的事情:

var result = dt.Select("RowNum > 1", "");

You can use Enumerable.Skipeven with a DataTablesince it is an IEnumerable<DataRow>:

Enumerable.Skip甚至可以使用a,DataTable因为它是一个IEnumerable<DataRow>

IEnumerable<DataRow> allButFirst = table.AsEnumerable().Skip(1);

get a new DataTablewith:

获得新DataTable的:

DataTable tblAllButFirst = allButFirst.CopyToDataTable();

If your next question is how you can take only rows with given indices:

如果您的下一个问题是如何仅获取具有给定索引的行:

var allowedIndices = new[]{ 2, 4, 7, 8, 9, 10 };
DataTable tblAllowedRows = table.AsEnumerable()
                                .Where((r, i) => allowedIndices.Contains(i))
                                .CopyToDataTable();