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

2

7

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;
Kimberlykimberlyn answered 17/10, 2012 at 9:10 Comment(0)
I
6
var result = table.AsEnumerable()
                  .Where((row, index) => index > 1)
                  .CopyToDataTable()
Industrialism answered 17/10, 2012 at 9:17 Comment(0)
V
8

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();
Vries answered 17/10, 2012 at 9:12 Comment(1)
+1 What could be faster, than skipping first item and simply returning all remaining itemsPluri
I
6
var result = table.AsEnumerable()
                  .Where((row, index) => index > 1)
                  .CopyToDataTable()
Industrialism answered 17/10, 2012 at 9:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.