How to get N row from datatable in C#

Problem:

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];
                newDataTable.Rows.Add(row);
            }
            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:http://www.dotnetjalps.com/2013/01/how-to-get-n-row-from-datatable-in-csharp.html

Published Friday, January 18, 2013 2:00 AM by Jalpesh P. Vadgama
Filed under: ,

Comments

# re: How to get N row from datatable in C#

Thursday, January 17, 2013 3:44 PM by salemsalah

Amazing  and  i need it  on  several time  

thank you

# re: How to get N row from datatable in C#

Saturday, January 19, 2013 7:45 AM by famouspeople

I want to tell you that you use those following or go to expert for solutions.