Friday, November 6, 2009

How to select Top N Records from datatable

hi.
In a web application with asp.net, c# in i want to select Top N records fro datatable .this is possible in many ways.but preffered way are here.

We can select Top (N) records from data-table using LINQ.

//Suppose this is datatablse whic have 1000 records
DataTable dtAllRecords = new DataTable();
//(1)How to select Top 100
var AllRecords = from item in dtAllRecords.AsEnumerable()
select item;
var top100 = AllRecords.Take(100);
//(1)How To select Second 100 (records from 101 to 200)
var Second100 = AllRecords.Skip(100).Take(100);
/*
Using this Take and Skip method of LINQ we can easily select top N records from datatabse.
*/

Above code use two powerful methods of LINQ to select Top 100 and Second 100 records from datatabse. you can you Take and Skip methods to select Top(N) records from datatable

We can also select Top N records without using LINQ.
here is the sample code .

//Table with 20 records
DataTable dtDates = new DataTable();
dtDates.Columns.Add("Bdates");
for (int i = 0; i <>
{
dtDates.Rows.Add(DateTime.Now.AddDays(i));
}
//Want to select top 10 from above Datatatable
DataTable dtTop10 = dtDates.Clone();
Int32 N = 0;
while (N <>
{
dtTop10.ImportRow(dtDates.Rows[N]);
N++;
}


Hope this will help.

thanks.