I was trying to figure out how to sort and select top 20 from a DataTable. Understand from the reading, DataTable have no "select top" feature. Some suggest use below method
DataTable outputTable = SourceTable.Clone();
for(int i=0;i<20;i++)
outputTable.ImportRow(SourceTable.Rows[i]);
In my case, i need to sort my DataTable oldTable and select top 20 after the sorting. I use DataView dView to sort it and copy it into a new DataTable newTable. For the display purpose, i use "for loop" to select top 20 from the new DataTable newTable.
Sample Code:
int maxDisplay = 20;
DataView dView = oldTable.DefaultView;
dView.Sort = " [Count] DESC ";
DataTable newTable = dView.ToTable();
int dCount = newTable.Rows.Count;
if (maxDisplay > dCount )
maxDisplay = dCount ;
if (dCount > 0)
{
for (int i = 0; i < maxDisplay ; i++)
{
xxxxxx;
xxx + newTable.Rows[i]["name"].ToString();
xxxxxx;
}
}
1 comment:
Thanks a lot, it works great!
Post a Comment