Compact LINQ syntax for float ranges?
Is there a compact, 开发者_如何学Pythonbuilt-in way to generate a range of floats from min
to max
with a given step
?
E.g.: range(10, 20, 0.1) [but built-in].
You could do
Enumerable.Range(100, 100).Select(i => i / 10F)
But it isn't very descriptive.
No, there's nothing built in. It would be really easy to write your static method though. Something like:
public static IEnumerable<float> FloatRange(float min, float max, float step)
{
for (float value = min; value <= max; value += step)
{
yield return value;
}
}
EDIT: An alternative using multiplication, as suggested in comments:
public static IEnumerable<float> FloatRange(float min, float max, float step)
{
for (int i = 0; i < int.MaxValue; i++)
{
float value = min + step * i;
if (value > max)
{
break;
}
yield return value;
}
}
In MiscUtil I have some range code which does funky stuff thanks to Marc Gravell's generic operator stuff, allowing you:
foreach (float x in 10f.To(20f).Step(0.1f))
{
...
}
精彩评论