tags:

views:

948

answers:

6

Hi,

I have a DataTable that contains 2000 records.

How would you retrieve the first 100 records in the DataTable?

+10  A: 

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);
Mark Seemann
If he's using Framework 2.0, he won't have access to Take.
Rawling
@Rawling: Correct, but that information wasn't originally available...
Mark Seemann
I'm just jealous, I'm stuck on 2.0 myself too :-)
Rawling
A: 

This works for DB2.

select * from table
fetch first 100 rows only;
Brian Bay
A: 

and for mysql: select * from table limit 100

knittl
A: 

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

Rawling
A: 

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.

Oliver
A: 

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