Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Array of Increments

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?

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

like image 516
Kevin Brown Avatar asked May 23 '12 13:05

Kevin Brown


1 Answers

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()

Let's break it down:

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.

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()
}

Edit: 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.

like image 50
SPFiredrake Avatar answered Oct 15 '22 16:10

SPFiredrake