开发者

C#: retrieve the first n records from a DataTable

I have a DataTable that contains 2000 records.

How 开发者_开发知识库would you retrieve the first 100 records in the DataTable?


If it implements IEnumerable<T>:

var first100 = table.Take(100);

If the type in question only implements IEnumerable, you can use the Cast extention method:

var first100 = table.Cast<Foo>().Take(100);


This works for DB2.

select * from table
fetch first 100 rows only;


and for mysql: select * from table limit 100


You could use something like this, but restrict the foreach loop to 100 records.


And to make the list full, here is the statement for MS SQL:

Select top 5 * from MyTable2

And some other methods with MS SQL can be found here.


To get a list of the top n records in C# using the 2.0 framework:

DataTable dt = new DataTable();
var myRows = new List<DataRow>();

//no sorting specified; take straight from the top.
for (int i = 0; i < 100; i++)
{
   myRows.Add(dt.Rows[i]);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜