Search code examples
c#ranking

how to get the rank list of multiple number in a list using C#?


I have the following list in C#:

List<double> arr = new List<double> { 5, 10, 7, 15, 9, 21, 1 };

I want store their ranks in another list for example List<double> rank. Finally I want get the following:

6 3 5 2 4 1 7

How can I do this?


Solution

  • List<double> arr = new List<double> { 5, 10, 7, 15, 9, 21, 1 };
    
    var rankDict = arr.Distinct().OrderByDescending(num=>num)
        .Select((number, index) => new {Number = number, Rank = index})
        .ToDictionary(m => m.Number, m => m.Rank);
    
    var rankedArray = new List<double>();
    
    foreach(var num in arr)
    {
        rankedArray.Add(rankDict[num] + 1);
    }
    
    Console.WriteLine(string.Join("-", rankedArray));
    

    Fiddle - https://dotnetfiddle.net/7C5o52