C#中的VBA/Excel RANK [英] VBA/Excel RANK in C#

查看:104
本文介绍了C#中的VBA/Excel RANK的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从电子表格到C#中创建计算,并且我想知道C#是否具有与Excel中的Rank相似的方法?

I am working on creating calculations from a spreadsheet into C#, and I was wondering if C# has a similar method to Rank in Excel?

在Excel中排名

返回数字列表中数字的排名.一个等级 number是其相对于列表中其他值的大小. (如果您要 对列表进行排序,数字的排名就是其位置.)

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.)

语法

排名(编号,参考号,订单)

数字是您要查找其等级的数字.

Number is the number whose rank you want to find.

参考是数字列表的数组或对数字列表的引用. ref中的非数字值将被忽略.

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.

如果订单为0(零)或省略,则Microsoft Excel对数字的排名就好像 ref是按降序排列的列表.如果订单为任何非零 值,Microsoft Excel对数字进行排名,就好像ref是在其中排序的列表一样 升序.

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.

通过代码也可以实现相同的目的,但是我只是想检查一下我首先缺少什么.

The same can be achieved through code, but I just wanted to check if there was anything I was missing first.

推荐答案

可以的.

        SortedList<int, object> list = new SortedList<int, object>();
        // fill with unique ints, and then look for one
        int rank = list.Keys.IndexOf(i);

排名将从零开始递增.

您可以通过编写扩展方法来使其美观:

You could pretty it up by writing an extension method:

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);

...但是我不认为这是最明智的选择.

...but I'm not convinced its the most sensible thing to do.

这篇关于C#中的VBA/Excel RANK的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆