C# 数组特定范围内的最小值
大家! 如何在 C# 中获取特定范围内 int 数组的最小值? 例如: int[] 数组=新 int{1,2,3,4,5,6,7,8,76,45}; 我想获得第三个和第八个元素之间的最小值。 也许可以通过 LINQ 查询来获取?
Everybody!
How can I get minimal value of an int array in specific range in C#?
For example:
int[] array= new int{1,2,3,4,5,6,7,8,76,45};
And I want to get a minimal value between 3-rd and 8-th element.
Maybe it is possible to get via LINQ queries?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我想我也可以为此添加两便士。由于 Jason 反对我们说的是跳过了多少个而不是结束索引,因此我们可以添加一个简单的扩展方法:
然后:
根据口味调整扩展方法名称。 (命名很难,我不会花很长时间在这里想出一个好名字:)
I figure I may as well add my tuppence to this. As Jason objects to the fact that we're saying how many we're skipping rather than the end index, we can add a simple extension method:
Then:
Adjust the extension method name to taste. (Naming is hard, and I'm not going to spend ages coming up with a nice one here :)
编辑
实际上,上面的方法效率很低,因为它枚举了整个序列,即使我们对索引高于 7 的项目不感兴趣。更好的解决方案是使用
TakeWhile
:不幸的是它的可读性不是很好...使其变得更好的最佳选择可能是创建一个自定义扩展方法,如乔恩的答案所示。
EDIT
Actually, the approach above is quite inefficient, because it enumerates the whole sequence, even though we're not interested in items with an index higher than 7. A better solution would be to use
TakeWhile
:Unfortunately it's not very readable... The best option to make it nicer is probably to create a custom extension method, as shown in Jon's answer.
只是添加另一个选项:
据我所知,如果您必须在接近末尾的范围内进行操作,并且您的数组真的很长,那么“理论上”会更快。
这是因为(再次据我所知)
Skip()
没有考虑到这是一个数组(即可以在 O(1) 中随机访问)并枚举它。Just to add another option:
AFAIK, this is "theorically" faster if you have to take a range near to the end of the one, and your array is really really long.
That's because (again AFAIK)
Skip()
doesn't take into account that is an array (i.e. can be accessed randomly in O(1)) and enumerates it anyway.就我个人而言,我更喜欢这样:
Personally, I'd prefer this: