How to select rows from DataTable based on Index / Row Number?
Solution 1
var result = table.AsEnumerable()
.Where((row, index) => index > 1)
.CopyToDataTable()
Solution 2
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();
Furqan Safdar
Technology enthusiast passionate about using design approaches and software architecture. Area of expertise are Dynamics 365, Power Platform, web and windows development using .NET, C#, WPF, WCF, ASP.net Core, Blazor, Microsoft Azure, Dynamics 365 and SharePoint
Updated on July 09, 2022Comments
-
Furqan Safdar almost 2 years
I have a
DataTable
. I want to select the rows based on theIndex
/Row Number
of the rows inDataTable
.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 exampleIndex > 2
, In that case First entry at Index 1,A001 | John
, will not become part of the resultantDataTable
. How can i do it efficiently?Moreover, i want to have my result both in the form of
DataTable
andLinq
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;