using LINQ retrieve top N rows

Normally to return top N rows we use an SQL statement similar to the one belowSelect top N * from table
 but How can we achieve the same thing in DataTableI have seen many examples, using different methods. Most of the methods centered around the idea of creating new columns with automatic values increment and using them as index 
 There is better method using LINQ 
 public  DataTable GetTopNFromDataTable(int TopRowCount, DataTable dtSource)
        {

            
var dtTrec = from item in 
dtSource.AsEnumerable()
                         
select 
item;
            
var 
topN = dtTrec.Take(TopRowCount);
            
DataTable dtNew = new DataTable
();
            dtNew = dtSource.Clone();

            
foreach (DataRow drrow in 
topN.ToArray())
            {

                dtNew.ImportRow(drrow);
            }

            
return 
dtNew;
        }
  var dtTrec - stores the item in datatable, Using the Take function of Linq the first N rows is filtered

            
var topN = dtTrec.Take(TopRowCount);
 

Now how to retrieve the rows between N1 & N2, just use the skip function along with Take as shown below

  public DataTable GetTopBetweenFromDataTable(int intFrom, int intTo, DataTable dtSource)
        {
......   var topN = dtTrec.Skip(intFrom).Take(intFrom); ......} 

2 Comments

  • Regarding this article with Mozilla Firefox 3.6.13, the arcticle code is not completely displayed - please check your styling-code.
    Thanks in advance
    Theo Fontane

  • Thanks for the snippet, it was exactly what I was looking for.

    BTW: You'll need to add a reference to System.Data.DataSetExtensions for the "AsEnumerable()" method to showup in the datatable.

Comments have been disabled for this content.