Search code examples
c#visual-studiodatatablesortingdataview

How to sort dataset.table[0] then get the top 10?


I'm adding an auto increment column (called "rowNum") to my table and it's working good, after that I use this code to sort datatable rows :

DataView dv = MyDataSet.Tables[0].DefaultView;
dv.Sort = "columnName DESC";

where columnName is one of my columns (not the auto increment one).

Now,The problem is: when I want to get the top 10 rows I use this code :

dv.RowFilter = "rowNum <= 10";

The result is not what I want, because when I do dv.Sort the rowNum shuffled (becomes in wrong order).

How can I get top 10 rows after sorting rows?


Solution

  • I prefer LINQ for stuff like this. Instead, I use System.Linq and write:

    var rows = MyDataSet.Tables[0].AsEnumerable()
       .OrderByDescending(r => r["columnName"]) 
       .Take(10);
    

    and then just bind to "rows".