开发者

Data table select top 5 rows

开发者 https://www.devze.com 2023-01-07 10:01 出处:网络
Hi is there any way to sel开发者_高级运维ect top 5 rows from a data table without iteration?I think, You can use LINQ:

Hi is there any way to sel开发者_高级运维ect top 5 rows from a data table without iteration?


I think, You can use LINQ:

datatable.AsEnumerable().Take(5);


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.


This is what worked for me:

datatable.Rows.Cast<System.Data.DataRow>().Take(5);


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);


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');
0

精彩评论

暂无评论...
验证码 换一张
取 消