Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 242
Furqan Safdar Avatar asked Oct 17 '12 09:10

Furqan Safdar


1 Answers

I am trying to do something like this:

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

You can use Enumerable.Skip even with a DataTable since it is an IEnumerable<DataRow>:

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

get a new DataTable with:

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();
like image 197
Tim Schmelter Avatar answered Sep 22 '22 15:09

Tim Schmelter