Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select top n rows from a datatable/dataview in ASP.NET

How to the select top n rows from a datatable/dataview in ASP.NET? Currently I am using the following code, passing the table and number of rows to get the records. 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; } 
like image 790
skamale Avatar asked May 07 '10 09:05

skamale


People also ask

How do I access DataView rows?

You can access the DataRow that is exposed by the DataRowView by using the Row property of the DataRowView. When you view values by using a DataRowView, the RowStateFilter property of the DataView determines which row version of the underlying DataRow is exposed.

Can you use a DataView to filter rows in a DataTable?

After a DataView has been created from a DataTable or LINQ to DataSet query, you can use the RowFilter property to specify subsets of rows based on their column values. The string-based and expression-based filters are mutually exclusive.

What is the difference between DataView and DataTable?

1. DataView can be used to select the data. Datatable can be used to edit or select or delete or insert a data. Means that Dataview is read only where as Datatable is read/Write.

What is DataView in asp net?

A DataView enables you to create different views of the data stored in a DataTable, a capability that is often used in data-binding applications. Using a DataView, you can expose the data in a table with different sort orders, and you can filter the data by row state or based on a filter expression.


2 Answers

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

Otherwise the way you mentioned

like image 103
Midhat Avatar answered Oct 15 '22 00:10

Midhat


I just used Midhat's answer but appended CopyToDataTable() on the end.

The code below is an extension to the answer that I used to quickly enable some paging.

int pageNum = 1; int pageSize = 25;  DataTable dtPage = dt.Rows.Cast<System.Data.DataRow>().Skip((pageNum - 1) * pageSize).Take(pageSize).CopyToDataTable(); 
like image 40
OldSchoolAde Avatar answered Oct 14 '22 22:10

OldSchoolAde