我有一个查询,我从数据库中获取一些列,这是简单的选择语句,然后我将列添加到此数据表中:
dt.Columns.Add(new DataColumn("ratio", typeof(double)));
然后我有另一个名为 Rank 的列,它再次手动添加如下:
dt.Columns.Add(new DataColumn("Rank", typeof(int)));
现在我如何首先按比率排序,然后使用比率添加排名,例如比率越高,排名越高,例如,如果比率为 3、5 和 9,一旦按比率排序,则应为:
rank ratio
1 9
2 5
3 3
编辑:
比率是通过除以我的查询中的两列来计算的
foreach (DataRow row in dt.Rows)
{
row["Ratio"] = (Convert.ToDecimal(row["LastMonth"]) / NoOfBranches).ToString("0.##");
}
谢谢
最佳答案
使用您提供给我们的信息和限制,我将建议下一个代码:
dt.Columns.Add(new DataColumn("Ratio", typeof(double)));
dt.Columns.Add(new DataColumn("Rank", typeof(int)));
foreach (DataRow row in dt.Rows)
{
row["Ratio"] =
(Convert.ToDecimal(row["LastMonth"]) / NoOfBranches).ToString("0.##");
}
//sorting the DataTable using the new DataColumn
dt.DefaultView.Sort = "Ratio DESC";
//after the sort, set the rank for each one
int rank = 1;
foreach (DataRow row in dt.Rows)
{
row["Rank"] = rank++;
}
示例摘自 forum post .
关于c# - 使用比率对数据表进行排序和排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9604639/