使用比率对数据表和排名进行排序

时间:2012-03-07 15:48:44

标签: c# sql sorting datacolumn

我有一个查询,我从数据库中获取一些列,这是简单的select语句然后我将列添加到此数据表中:

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.##");
 }

由于

3 个答案:

答案 0 :(得分:2)

使用您给我们的信息和restrinctions ,我会建议下一个代码:

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中提取的示例。

答案 1 :(得分:1)

直接从db:

SELECT RANK() OVER (ORDER BY ratio DESC) AS rank,ratio FROM [YourTableName]

答案 2 :(得分:1)

如果你想从世界的C#方面做到这一点:

DataTable dt = new DataTable();
dt.DefaultView.Sort = "ratio DESC";
dt.Columns.Add(new DataColumn("Rank", typeof(int)));
int count = 1;
foreach (DataRowView dr in dt.DefaultView)
{
    dr["Rank"] = count++;
}

每当使用DataTable时,您需要引用dt.DefaultView,因为它是表的排序版本。有关详细信息,请参阅MSDN:

http://msdn.microsoft.com/en-us/library/system.data.datatable.defaultview.aspx