使用给定的步数获取给定最小值和最大值的可枚举范围 [英] Get an enumerable range for a given min and max with a given number of steps

查看:39
本文介绍了使用给定的步数获取给定最小值和最大值的可枚举范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我熟悉 枚举.Range 方法用于生成值的枚举.但我想要一些稍微不同的东西.我想提供最小值、最大值和所需的点数.

I am familiar with the Enumerable.Range method for generating an enumeration of values. But I would like something slightly different. I want to provide a min value, max value, and a number of desired points.

IE:

Method(double min, double max, int numberOfSteps)

采取

方法(0, 1000, 11);

会回来

0, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000

我想像这样的东西,一定有一个内置的方法,但我的搜索没有找到任何东西.我错过了什么吗?

I figure for something like this, there must be a built-in method but my search hasn't turned anything up. Am I missing something?

推荐答案

除了您希望值是 double 之外,其他一切都可以使用 Enumerable.Range.我不认为有任何内置的东西可以做你想做的事,但在 Enumerable.Range 之上实现是微不足道的:

Other than the fact that you want the values to be double, everything else can be done with Enumerable.Range. I don't think there's anything built-in to do what you want, but it's trivial to implement on top of Enumerable.Range:

return Enumerable.Range(0, steps)
                 .Select(i => min + (max - min) * ((double)i / (steps - 1)));

我写得有点仔细,所以你总是得到最终的价值.如果你说你只想要一个步骤,它确实很无聊......你可能想要防止这种情况并在这种情况下使用 Enumerable.Repeat(min, 1) .

I've written that somewhat carefully so that you always end up with the final value. It does bork if you say you only want a single step though... you might want to guard against that and use Enumerable.Repeat(min, 1) in that case.

这篇关于使用给定的步数获取给定最小值和最大值的可枚举范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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