Generate number sequence with step size in linq

时间:2018-07-24 10:17:15

标签: c# 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);
}

4 个答案:

答案 0 :(得分:1)

尝试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));

结果:

1, 6, 11

答案 1 :(得分:1)

如果要模仿程序代码,可以使用TakeWhile

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

但是我认为这在性能和可读性方面更糟。

答案 2 :(得分:1)

在LINQ中不必做任何事情 就可以像 Linq一样使用,您可以非常接近原始版本:

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

称呼它

var numbers = CustomSequence();

或对其进行任何进一步的LINQ:

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

答案 3 :(得分:0)

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.