从动态数据表中获取前10或20行 [英] take top 10 or 20 rows from dynamic datatable

查看:74
本文介绍了从动态数据表中获取前10或20行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Datable中说有100条记录

I have 100 records in my Datable says to be in

DataTable dt=new DataTable();

dt 的记录中有 100 条记录,列名称为 sub_id(包含int数据类型) subheadername(包含nvarchar(150))),我希望此 dt 的前 20条记录升序顺序

dt have 100 of records say column name as sub_id(contain int datatype) and subheadername(contain nvarchar(150)) , I want top 20 records from this dt in ascending order

我将代码放置为

//dtlcategories.DataSource = dt.AsEnumerable().OrderBy(x => x["subheadername"]).Take(20).ToList();
dtlcategories.DataSource = dt.Rows.Cast<DataRow>().OrderBy(x => x["subheadername"]).Take(20).ToList();
dtlcategories.DataBind();

此处dtlcategories是数据列表",但在运行时出现错误,因为"System.Data.DataRow"不包含名称为"subheadername"的属性.

Here dtlcategories is Datalist but on running error is coming as 'System.Data.DataRow' does not contain a property with the name 'subheadername'.

已解决答案

dtlcategories.DataSource = dt.Rows.Cast<DataRow>().OrderBy(x => x["subheadername"]).Take(20).copytodatatable();
dtlcategories.DataBind();

推荐答案

使用LINQ,有两种不同的方法可以做到这一点.这些都将返回相同的结果.

There's a couple different ways you can do this using LINQ. These will both return the same results.

dt.AsEnumerable().OrderBy(x => x["subheadername"]).Take(20);

dt.Rows.Cast<DataRow>().OrderBy(x => x["subheadername"]).Take(20);

如果要将结果用作另一个控件的数据源,则可能需要在 .Take(x)之后调用 .ToList().

If you're going to use the result as the source of data for another control, you may need to call .ToList() after .Take(x).

我根据您的修改更改了列名.如果要改为按ID排序(未指定),只需将"subheadername"替换为"sub_id".

I changed the column name based on your edit. If you want to sort by id instead (you didn't specify), just replace "subheadername" with "sub_id".

这篇关于从动态数据表中获取前10或20行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆