Gaby
Gaby

Reputation: 3033

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?

Upvotes: 3

Views: 8653

Answers (6)

p.campbell
p.campbell

Reputation: 100577

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

Upvotes: 0

Oliver
Oliver

Reputation: 45101

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.

Upvotes: 0

Rawling
Rawling

Reputation: 50114

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

Upvotes: 0

Mark Seemann
Mark Seemann

Reputation: 233150

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

Upvotes: 10

knittl
knittl

Reputation: 265251

and for mysql: select * from table limit 100

Upvotes: 0

Brian Bay
Brian Bay

Reputation: 301

This works for DB2.

select * from table
fetch first 100 rows only;

Upvotes: 0

Related Questions