Friday, November 6, 2009

How to select Top N Records from datatable

In a web application with, 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();
for (int i = 0; i <>
//Want to select top 10 from above Datatatable
DataTable dtTop10 = dtDates.Clone();
Int32 N = 0;
while (N <>

Hope this will help.



  1. I feel first one is the efficient w.r.t TimeComplexity.


  2. This comment has been removed by the author.


Comments posted on ASP.Net Ajax Tutorials Blog are moderated and will be approved only if they are on-topic and not abusive. Please email me or my team for tech-support or blogging related questions. Avoid including website URLs in your comments - Thanks Author