문제

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
도움이 되었습니까?

해결책 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();
        }
    }

다른 팁

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).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top