Search code examples
c#linqsequence

Get a sequence of multiples of an integer between two values using LINQ


OK the title is ugly but the problem is quite straightforward:

I have a WPF control where I want to display plot lines. My "viewport" has its limits, and these limits (for example, bottom and top value in object coordinates) are doubles.

So I would like to draw lines at every multiple of, say, 5. If my viewport goes from -8.3 to 22.8, I would get [-5, 0, 5, 10, 15, 20].

I would like to use LINQ, it seems the natural candidate, but cannot find a way...

I imagine something along these lines:

int nlines = (int)((upper_value - lower_value)/step);
var seq = Enumerable.Range((int)(Math.Ceiling(magic_number)), nlines).Select(what_else);

Given values are (double)lower_value, (double)upper_value and (int)step.


Solution

  • Try this code:

    double lower_value = -8.3;
    double upper_value = 22.8;
    int step = 5;
    
    int low = (int)lower_value / step;
    int up = (int)upper_value / step;
    
    var tt = Enumerable.Range(low, up - low + 1).Select(i => i * step);
    

    EDIT This code is intended for all negative values of the lower_value and for positive values which are divisible by the step. To make it work for all other positive values as well, the following correction should be applied:

    if (lower_value > step * low)
        low++;