Question

This is the code I currently have which is working just that when the students score are the same they get different ranks which is not what I would like

class Program
{
    static void Main(string[] args)
    { 
        using (var db = new SchoolEntities())
        {
            int rank= 0;
            var query = db.ScoreSummaries
                .OrderByDescending(x => x.TotalScore).ToList();

            foreach (var item in query)
            {
                rank+= 1;
                Console.WriteLine("{0},{1},{2}", item.TransactionID, item.TotalScore, rank);
            }
            Console.WriteLine("Pls press any key to exit");
            Console.ReadKey();
        }
    }

My result is as follows, notice that the first two records are the same but have different ranks. I would like both records to have a rank of 1 and the next one a rank of 3. Any suggestion would be appreciated

TRANS01,92,1
TRANS01,92,2
TRANS01,88,3
TRANS01,85,4
TRANS01,79,5
Pls press any key to exit
Was it helpful?

Solution 2

The way i would do it is. save your current score to new variable

 static void Main(string[] args)
    { 
        using (var 

db = new SchoolEntities())
        {
            double currentScore = 0;
            int rank= 0;
            int savedRank;
        var query = db.ScoreSummaries
            .OrderByDescending(x => x.TotalScore).ToList();

        foreach (var item in query)
        {

      rank+= 1;
      if(item.TotalScore == current score)
       {
        savedRank = savedRank
       }
       else
       {
         savedrank = rank;
        }

            Console.WriteLine("{0},{1},{2}", item.TransactionID, item.TotalScore, savedrank);
            currentScore = item.totalScore;
            }
            Console.WriteLine("Pls press any key to exit");
            Console.ReadKey();
        }
    }

OTHER TIPS

Try something like this

        int rank= 0;
        int lastScore = 0;
        var query = db.ScoreSummaries
            .OrderByDescending(x => x.TotalScore).ToList();

        foreach (var item in query)
        {
            if (lastScore > item.TotalScore)
                rank++;

            lastScore = item.TotalScore;
            Console.WriteLine("{0},{1},{2}", item.TransactionID, item.TotalScore, rank);
        }

I'll assume that this is an assignment for some class.

You are trying to keep track of the current rank of a student, along with the total number of students that you have gone through. To do this, you'll need to keep track of each in their own variable, and modify them at the appropriate times.

The number of students that you've gone through can be incremented each time, like your rank variable currently is; the current_rank variable will need to be incremented separately from that (maybe based on the previous student's grade, hint, hint).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top