Mike
Mike

Reputation: 379

sort numbers and get the rank in c#

How can we sort a double[] array in c# and get the ranks. For instance consider sorting

[4 5 3 1 6] 

in descending order.

I want to map each element to its index in the sorted list. For example, if I sort the list I'll get [6 5 4 3 2 1], so 6's index is 1, 5's index is 2 and so on. The desired output would be:

[3     2     4     5     1]

I searched a lot but found nothing

Upvotes: 1

Views: 3496

Answers (1)

brz
brz

Reputation: 6016

using Linq:

    private static void Main(string[] args)
    {
         var ints = new[] { 4, 5, 3, 1, 6 };
         foreach (var item in ints.Select((x, i)=>new { OldIndex = i, Value = x, NewIndex = -1})
                                  .OrderByDescending(x=>x.Value)
                                  .Select((x, i) => new { OldIndex = x.OldIndex, Value = x.Value, NewIndex = i + 1})
                                  .OrderBy(x=>x.OldIndex))
             Console.Write(item.NewIndex + " ");

    }

Upvotes: 1

Related Questions