C#数组在特定范围内的最小值

Noz*_*zim 4 .net c# arrays min

大家好!如何在C#中获取特定范围内的int数组的最小值?例如:int [] array = new int {1,2,3,4,5,6,7,8,76,45}; 我希望在第3和第8个元素之间得到一个最小值.也许有可能通过LINQ查询?

dec*_*one 13

array.Skip(2).Take(5).Min();
Run Code Online (Sandbox Code Playgroud)

  • @Jason:跳过2个项目,拿5个项目,然后得到分钟.什么不清楚? (6认同)
  • @nozim:不,这不是因为它不能立即清楚它在做什么.它很聪明,看起来很聪明,但它不是最易读的解决方案,因此应该被拒绝.抱歉. (3认同)
  • @Jon Skeet:我觉得这里错过了一点,特别是如果你不同意的话.是的,这是可以理解的,它正在跳过两个,取五个并找到分钟.目前尚不清楚的是,它正在解决手头的问题.我需要花一点时间思考(尽管很小),而我之前指出的解决方案却没有.我觉得这是因为聪明因素而得到投票(聪明的代码很糟糕!). (3认同)

Jon*_*eet 6

我想我也可以加入我的tuppence.由于Jason反对这样一个事实,即我们说的是跳过了多少而不是结束索引,我们可以添加一个简单的扩展方法:

public static IEnumerable<T> WithIndexBetween<T>(this IEnumerable<T> source,
    int startInclusive, int endExclusive)
{
    // The two values can be the same, yielding no results... but they must
    // indicate a reasonable range
    if (endExclusive < startInclusive)
    {
        throw new ArgumentOutOfRangeException("endExclusive");
    }
    return source.Skip(startInclusive).Take(endExclusive - startInclusive);
}
Run Code Online (Sandbox Code Playgroud)

然后:

int min = array.WithIndexBetween(2, 7).Min();
Run Code Online (Sandbox Code Playgroud)

调整扩展方法名称以尝试.(命名很难,而且我不会花很多时间在这里找到一个好的:)