Taking on the values โโof start
, end
and increment
, you can abstract this further:
Enumerable .Repeat(start, (int)((end - start) / increment) + 1) .Select((tr, ti) => tr + (increment * ti)) .ToList()
Let me break it:
Enumerable.Repeat
takes a starting number, repeats the specified number of elements and returns an enumerated (collection). In this case, we start with the start
element, find the difference between start
and end
and divide it by 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 items to use. Just keep in mind that since increment
is decimal / double, there may be rounding errors when passing to int.
Select
converts all elements of an enumerated value specified by a particular selection function. In this case, we take the number that was generated and the index, and add the original number with the index times the increment.
Finally, a call to ToList
save the collection in memory.
If you often use this, you can create a way to do this:
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 use replay so that non-integer values โโwill be saved. Also, error checking is not performed here, so you have to make sure that increment
not 0 and that start
< end * sign(increment
). The reason for multiplying the end by the sign of the increment is that if you increase a negative number, then the end must be before the start.