增量C#数组 [英] C# Array of Increments

查看:129
本文介绍了增量C#数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我要生成由0.01从1到6递增一个数组,什么是最有效的方式做到这一点?

If I want to generate an array that goes from 1 to 6 and increments by .01, what is the most efficient way to do this?

我要的是一个数组,以分钟,MAXS受到以后更改......像这样: X [1,1.01,1.02,1.03 ...]

What I want is an array, with mins and maxs subject to change later...like this: x[1,1.01,1.02,1.03...]

推荐答案

假设启动结束递增值,就可以摘要进一步:

Assuming a start, end and an increment value, you can abstract this further:

Enumerable
    .Repeat(start, (int)((end - start) / increment) + 1)
    .Select((tr, ti) => tr + (increment * ti))
    .ToList()

让我们来分析一下:

Enumerable.Repeat 需要一个起始数字,重复的元素给定数量,并返回一个枚举(集合)。在这种情况下,我们开始与启动元素中,找到之间结束的差异开始并通过递增把它(这为我们提供了增量之间开始数结束),并添加一个包含原来的号码。这应该给我们的元素使用的数量。一定要小心,因为递增是一个十进制/双,当你转换为一个int可能有舍入误差。

Enumerable.Repeat takes a starting number, repeats for a given number of elements, and returns an enumerable (a collection). In this case, we start with the start element, find the difference between start and end and divide it by the increment (this gives us the number of increments between start and end) and add one to include the original number. This should give us the number of elements to use. Just be warned that since the increment is a decimal/double, there might be rounding errors when you cast to an int.

选择转换赋予了特定的选择器功能可枚举的所有元素。在这种情况下,我们采取的指数生成的数量,并增加与索引乘以增量原始数

Select transforms all elements of an enumerable given a specific selector function. In this case, we're taking the number that was generated and the index, and adding the original number with the index multiplied by the increment.

最后,调用了ToList 将收集保存到内存中。

Finally, the call to ToList will save the collection into memory.

如果你发现自己经常利用这一点,那么您可以创建为你做这一个方法:

If you find yourself using this often, then you can create a method to do this for you:

public static List<decimal> RangeIncrement(decimal start, decimal end, decimal increment)
{
    return Enumerable
        .Repeat(start, (int)((end - start) / increment) + 1)
        .Select((tr, ti) => tr + (increment * ti))
        .ToList()
}

编辑:改为使用重复,使非整数值仍将维持。此外,还有没有错误检查这里正在做,所以你应该确保检查递增不为0和启动&LT; 结束*号(增量)。之所以通过增量的迹象乘以到底是,如果你用一个负数递增,到底应该开始之前。

Changed to using Repeat, so that non-whole number values will still be maintained. Also, there's no error checking being done here, so you should make sure to check that increment is not 0 and that start < end * sign(increment). The reason for multiplying end by the sign of increment is that if you're incrementing by a negative number, end should be before start.

这篇关于增量C#数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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