如何找到数组中N个最高数字?

时间:2019-05-23 17:47:29

标签: c# asp.net arrays .net

我需要编写一个在数组中查找N个最高数字的函数。

我什么也没尝试。甚至不知道从哪里开始。

public int marathon(int input1,int input2, int[] input3)
{
    //  this is the function, ignore first input its not relevant input 2 is 
    //  N(How much highest numbers you want from array )
}

如果将2作为输入2,并且数组看起来像这样{1,2,3,4},则输出将为3和4

2 个答案:

答案 0 :(得分:2)

一点lambda就能解决问题。

var top = new[] { 1, 2, 3, 4 }.OrderByDescending(num => num).Take(N);

答案 1 :(得分:0)

通过LINQ:只需对数组排序并获取前N个项目。扩展方法的示例:

public static class ExtensionMethods
{
    public static IEnumerable<T> TakeHighests<T>(this IEnumerable<T> collection, int count)
    {
        return collection.OrderByDescending(i => i) // Sort the enumerable (arrays are also enumerables). Use OrderBy() for N lowest items
            .Take(count) // Take only `count` items
    }
}

采用2个最高值的示例:

int[] arr = ...;
int[] twoHighests = arr.TakeHighests(2).ToArray();
相关问题