How to sort dataset.table[0] then get the top 10?
-
07-07-2019 - |
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?
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