Reputation: 219
Hi is there any way to select top 5 rows from a data table without iteration?
Upvotes: 9
Views: 43734
Reputation: 387
This works for my needs.
public static DataTable TopRows(this DataTable dTable, int rowCount)
{
DataTable dtNew = dTable.Clone();
dtNew.BeginLoadData();
if (rowCount > dTable.Rows.Count) { rowCount = dTable.Rows.Count; }
for (int i = 0; i < rowCount;i++)
{
DataRow drNew = dtNew.NewRow();
drNew.ItemArray = dTable.Rows[i].ItemArray;
dtNew.Rows.Add(drNew);
}
dtNew.EndLoadData();
return dtNew;
}
to use it you then do this:
dataTable.TopRows(5);
Upvotes: 0
Reputation: 1919
This is what worked for me:
datatable.Rows.Cast<System.Data.DataRow>().Take(5);
Upvotes: 0
Reputation: 1
Using 2 of the above posts, the following works for me:
foreach (DataRow _dr in DataSet.Tables[<tblname>].Select("", "Timestamp DESC").AsEnumerable().OfType<DataRow>().Take(5))
So now you can normally filter if you want, order if you want and then get only the amount of records that you want and then iterate through them whether it is 1 or 100.
Hope that helps someone.
Upvotes: 0
Reputation: 48547
If you use a LINQ statement, you could use the Take()
method.
This post may be of some assistance as well.
EDIT
As you are using VS2005, use the SELECT()
method in the datatable like so:
DataRow[] rows = datatable.Select('TOP 5');
Upvotes: -3
Reputation: 1858
I think, You can use LINQ:
datatable.AsEnumerable().Take(5);
Upvotes: 17