Reputation: 107
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
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
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
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
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