Search code examples
c#asp.netranking

How to Calculate students Rank based on the Total, If the Total amount repeated twice then the rank should be same


Here what I tried :

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

While I am looping it should check some condition, can any one help me ?


Solution

  • You need to access previous row value while looping. Go with traditional for loop. Be careful for the first record as there will be previous row for it.

    for( int i = 0; i < dt.DefaultView.Rows.Count; i++ )
    {
        if( i > 0 )
        {
           // Compare with previous row using index
           if( dt.DefaultView.Rows[i]["ratio"] == dt.DefaultView.Rows[i-1]["ratio"])
           {
               dt.DefaultView.Rows[i]["Rank"] = count;
           }
          else
          {
              dt.DefaultView.Rows[i]["Rank"] = count++;
          }
        }
       else
       {
           dt.DefaultView.Rows[i]["Rank"] = count;
       } 
    
    }