1

I have a query where i get some columns from database it is simple select statement then I add columns to this datatable as :

dt.Columns.Add(new DataColumn("ratio", typeof(double)));

Then I have another column called Rank which is again added manually as follow :

dt.Columns.Add(new DataColumn("Rank", typeof(int)));

now how do I first of all sort by ratio and then add rank using the ratio e.g. the higher the ratio the higher the rank for example if ratio is 3, 5 and 9 once ordered by ratio it should be :

rank ratio
1    9
2    5
3    3

EDIT :

the ratio is calculated by dividing the two columns in my query

 foreach (DataRow row in dt.Rows)
 {
row["Ratio"] = (Convert.ToDecimal(row["LastMonth"]) / NoOfBranches).ToString("0.##");
 }

Thanks

4

3 回答 3

2

使用您给我们的信息和限制,我将建议下一个代码:

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++;
}

从论坛帖子中提取的示例。

于 2012-03-07T16:11:15.077 回答
1

直接从数据库:

SELECT RANK() OVER (ORDER BY ratio DESC) AS rank,ratio FROM [YourTableName]
于 2012-03-07T15:57:46.523 回答
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

于 2012-03-07T15:59:33.447 回答