我正在将电子表格中的计算创建到 C# 中,我想知道 C# 是否具有与 Excel 中的排名类似的方法?
Excel 中的排名
Returns the rank of a number in a list of numbers. The rank of a number is its size relative to other values in a list. (If you were to sort the list, the rank of the number would be its position.)
Syntax
RANK(number,ref,order)
Number is the number whose rank you want to find.
Ref is an array of, or a reference to, a list of numbers. Nonnumeric values in ref are ignored.
Order is a number specifying how to rank number.
If order is 0 (zero) or omitted, Microsoft Excel ranks number as if ref were a list sorted in descending order. If order is any nonzero value, Microsoft Excel ranks number as if ref were a list sorted in ascending order.
同样可以通过代码实现,但我只是想先检查一下我是否遗漏了什么。
最佳答案
你可以,有点。
SortedList<int, object> list = new SortedList<int, object>();
// fill with unique ints, and then look for one
int rank = list.Keys.IndexOf(i);
排名将是一个从零开始的递增位置。
您可以通过编写扩展方法来美化它:
public static class Extensions
{
public static int Rank(this int[] array, int find)
{
SortedList<int, object> list = new SortedList<int, object>();
for (int i = 0; i < array.Length; i++)
{
list.Add(array[i], null);
}
if (list.ContainsKey(find))
{
return list.Keys.IndexOf(find);
}
else
{
return -1;
}
}
}
像这样使用它:
int[] ints = new int[] { 2, 7, 6, 3, 9, 12 };
int rank = ints.Rank(2);
...但我不认为这是最明智的做法。
关于c# - C# 中的 VBA/Excel RANK,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21337900/