如果all arr 中的项distinct,你可以创建一个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);
然后使用ranks 找出给定相应排名的项目:
int rankOf5 = ranks[5]; // 6
测试
string test = string.Join(" ", arr.Select(x => ranks[x]));
// 6 3 5 2 4 1 7
Console.Write(test);
编辑:使用循环测试:
foreach (var item in arr)
Console.Write(ranks[item]);
或者
for (int i = 0; i < arr.Count; ++i)
Console.Write(ranks[arr[i]]);
编辑 2 如果arr 可以有重复,例如
// 21 appears 2 times
List<double> arr = new List<double> { 5, 10, 7, 15, 9, 21, 21, 1 };
您可能想要计算所谓的密集排名
var ranks = arr
.GroupBy(item => item)
.OrderByDescending(chunk => chunk.Key)
.Select((chunk, index) => new {
item = chunk.Key,
rank = index + 1
})
.ToDictionary(x => x.item, x => x.rank);
string test = string.Join(" ", arr.Select(x => ranks[x]));
// 6 3 5 2 4 1 1 7
Console.Write(test);