Question

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?

Was it helpful?

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".

OTHER TIPS

if add .Take(10) in AsEnumerable() line is not working. but if add second line as mentioned below is working.

var Rows = (from row in dt.AsEnumerable() 
orderby row["CostPerVeteran"] descending
select row);

dtChart = Rows.Take(10).CopyToDataTable();

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top