views:

733

answers:

2

How to select top n rows from a datatable/dataview in asp.net.currently I am using the following code by passing the table and number of rows to get the records but is there a better way.

public DataTable SelectTopDataRow(DataTable dt, int count)

 {
     DataTable dtn = dt.Clone();
     for (int i = 0; i < count; i++)
     {
         dtn.ImportRow(dt.Rows[i]);
     }

     return dtn;
 }
+2  A: 

In framwork 3.5, dt.Rows.Cast<System.Data.DataRow>().Take(n)

Otherwise the way you mentioned

Midhat
+2  A: 

You could modify the query. If you are using SQL Server at the back, you can use Select top n query for such need. The current implements fetch the whole data from database. Selecting only the required number of rows will give you a performance boost as well.

Kangkan