chan4lk
chan4lk

Reputation: 107

Generate number sequence with step size in linq

I need to generate a sequence of numbers using C# linq. Here is how I have done it using for loop.

int startingValue = 1;
int endValue = 13;
int increment = 5;
for (int i = startingValue; i <= endValue; i += increment) {
   Console.WriteLine(i);
}

Upvotes: 1

Views: 3508

Answers (4)

vc 74
vc 74

Reputation: 38179

If you want to mimic your procedural code, you can use TakeWhile:

 Enumerable.Range(0, int.MaxValue).
            Select(i => startValue + (i * increment)).
            TakeWhile(i => i <= endValue);

But this is to my opinion worse in terms of performance and readability.

Upvotes: 3

nvoigt
nvoigt

Reputation: 77364

Not everthing has to be done in LINQ to be usasable like Linq, you can stick very close to your original:

IEnumerable<int> CustomSequence(int startingValue = 1, int endValue = 13, int increment = 5)
{        
    for (int i = startingValue; i <= endValue; i += increment) 
    {
        yield return i;
    }
}

Call it like

var numbers = CustomSequence();

or do any further LINQ on it:

var firstTenEvenNumbers = CustomSequence().Where(n => n % 2 == 0).Take(1).ToList();

Upvotes: 1

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239824

Seems wasteful but the best I can think of is something like this:

int startingValue = 1;
int endValue = 13;
int increment = 5;
var sequence = Enumerable.Range(startingValue,(endingValue-startingValue)+1)
               .Where(i=>i%increment == startingValue%increment);

Which is hopefully easy to follow. Logically, all of the values produced by your for loop are congruent to the startingValue modulo increment. So we just generate all of the numbers between startingValue and endingValue (inclusive) and then filter them based on that observation.

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186843

Try Enumerable.Range in order to emulate for loop:

int startingValue = 1;
int endValue = 13;
int increment = 5;

var result = Enumerable
  .Range(0, (endValue - startingValue) / increment + 1)
  .Select(i => startingValue + increment * i);

Console.Write(string.Join(", ", result));

Outcome:

1, 6, 11

Upvotes: 2

Related Questions