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; }
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.
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.
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.
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.
In framework 3.5, dt.Rows.Cast<System.Data.DataRow>().Take(n)
Otherwise the way you mentioned
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With