简体   繁体   English

在linq中生成步长的数字序列

[英]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

If you want to mimic your procedural code, you can use TakeWhile : 如果您想模仿程序代码,可以使用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. 但在我看来,这在性能和可读性方面更糟糕。

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. 所以我们只生成startingValueendingValue (包括)之间的所有数字,然后根据该观察结果对它们进行过滤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM