How to get N row from datatable in C#

Tags: ASP.NET, C#


Recently one of my friend was needed only first three rows of data table and so he asked me and I have multiple solutions for that. So thought it would be great idea to share with you guys.

Possible Solutions to problem:

There are two ways to solve this problem.

  1. With normal for loop
  2. With lamda expression and linq

1. With normal for loop:

Following is code from where we can get 3 rows of data table.

private  DataTable GetFirst3RowViaFor(DataTable dataTable) {
            DataTable newDataTable = dataTable.Clone();
            for(int i=0;i<3;i++)
                DataRow row = dataTable.Rows[i];
            return newDataTable;

Here in this way I have cloned data table structure and then I added first 3 rows of data table to new data table.

2. With lamda expression:

Following is a code for that. It’s very easy. I have used lamda expression to get first 3 rows.

private DataTable GetFirstThreeRowViaLinq(DataTable dataTable) {
            return dataTable.Rows.Cast().Take(3).CopyToDataTable();
That’s it. Hope you liked it. Stay tuned more updates..

Original blog post:


Comments have been disabled for this content.