Search code examples
c#linqdatatableindexingcriteria

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


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

Suppose below is the 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 DataTable using 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?

Moreover, i want to have my result both in the form of DataTable and Linq query outcome.

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;

Solution

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