Sawa Sawa - 3 months ago 10
C# Question

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?

Answer

If all the items in the arr are distinct, you can create a dictionary:

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

  var ranks = arr
    .OrderByDescending(item => item)
    .Select((item, index) => new {
      item = item,
      rank = index + 1,
    })
    .ToDictionary(x => x.item, x => x.rank);

And then use ranks to find out for the item given its corresponding rank:

    int rankOf5 = ranks[5]; // 6

Test

   string test = string.Join(" ", arr.Select(x => ranks[x]));

   // 6  3  5  2  4  1  7
   Console.Write(test);

Edit: Test with loops:

   foreach (var item in arr)
     Console.Write(ranks[item]);

Or

   for (int i = 0; i < arr.Count; ++i)
      Console.Write(ranks[arr[i]]);