Search code examples
c#.netlinqenumerableenumerable.range

How to get enumerable range with a variable step count


I am trying to get a list ranging from minimum and maximum values with variable step counts.

For example: If I set minimum value as 10,000, maximum value as 150,000 and step count as 20,000. I should be able to get list as [10000,30000,50000,70000,...,150000].

Similary if step count is set to 15,000 - I should get list as [10000,25000,40000,...,145000]

 int min = 10000;
 int max = 150000;
 int step = 20000;

 var result = Enumerable.Range( min, max).Where(i => i<= max && (i % step == 0));
 foreach (int num in result) { Console.WriteLine(num); } // output: [20000,40000,60000,80000,100000,120000,140000]

Since I am using modulus operator to equate zero value, it is skipping the first value in the range and gives me the above result instead of [10000,30000,..,150000]. Since I am very new to C# programming, can anyone please correct me with the above code to get the desired output.

PS: I have referred this thread How to get alternate numbers using Enumerable.Range? but was unable to find the answer.


Solution

  • You just need to modify the where condition in your Linq statement:

    var result = Enumerable.Range(min, max - min + 1).Where(i => (i - min) % step == 0);
    

    When equating whether the modulo of i vs step was 0, you forgot to subtract the starting value min. By subtracting min, you offset the modulo calculation to compare against the value that is i offset by min as opposed to using i.

    Output when step is 20,000:

    10000
    30000
    50000
    70000
    90000
    110000
    130000
    150000
    

    Output when step is 15,000:

    10000
    25000
    40000
    55000
    70000
    85000
    100000
    115000
    130000
    145000