Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

sequence

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.

like image 292
heltonbiker Avatar asked Dec 19 '22 15:12

heltonbiker


2 Answers

Enumerable.Range should do the trick:

Enumerable.Range(lower_value, upper_value - lower_value)
          .Where(x => x % step == 0);
like image 186
crthompson Avatar answered Apr 30 '23 11:04

crthompson


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++;
like image 31
Dmitry Avatar answered Apr 30 '23 11:04

Dmitry