[英]Generate number sequence with step size in linq
I need to generate a sequence of numbers using C# linq. 我需要使用C#linq生成一系列数字。 Here is how I have done it using for loop.
以下是我使用for循环的方法。
int startingValue = 1;
int endValue = 13;
int increment = 5;
for (int i = startingValue; i <= endValue; i += increment) {
Console.WriteLine(i);
}
Try Enumerable.Range in order to emulate for
loop: 尝试Enumerable.Range以模拟
for
循环:
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
Not everthing has to be done in LINQ to be usasable like Linq, you can stick very close to your original: 不是寄托都已经在LINQ做是usasable 像 LINQ的,你可以坚持非常接近你原来的:
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: 或者做任何进一步的LINQ:
var firstTenEvenNumbers = CustomSequence().Where(n => n % 2 == 0).Take(1).ToList();
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
. 逻辑上 ,
for
循环生成的所有值都与startingValue
模数increment
。 So we just generate all of the numbers between startingValue
and endingValue
(inclusive) and then filter them based on that observation. 所以我们只生成
startingValue
和endingValue
(包括)之间的所有数字,然后根据该观察结果对它们进行过滤。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.