How to create a sequence of integers in C#?
Solution 1
You can use Enumerable.Range(0, 10);
. Example:
var seq = Enumerable.Range(0, 10);
MSDN page here.
Solution 2
Enumerable.Range(0, 11);
Generates a sequence of integral numbers within a specified range.
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.range.aspx
Solution 3
You could create a simple function. This would work for a more complicated sequence. Otherwise the Enumerable.Range
should do.
IEnumerable<int> Sequence(int n1, int n2)
{
while (n1 <= n2)
{
yield return n1++;
}
}
Solution 4
Linq projection with the rarely used indexer overload (i):
(new int[11]).Select((o,i) => i)
I prefer this method for its flexibilty.
For example, if I want evens:
(new int[11]).Select((item,i) => i*2)
Or if I want 5 minute increments of an hour:
(new int[12]).Select((item,i) => i*5)
Or strings:
(new int[12]).Select((item,i) => "Minute:" + i*5)
Solution 5
In C# 8.0 you can use Indices and ranges
For example:
var seq = 0..2;
var array = new string[]
{
"First",
"Second",
"Third",
};
foreach(var s in array[seq])
{
System.Console.WriteLine(s);
}
// Output: First, Second
Or if you want create IEnumerable<int>
then you can use extension:
public static IEnumerable<int> ToEnumerable(this Range range)
{
for (var i = range.Start.Value; i < range.End.Value; i++)
{
yield return i;
}
}
...
var seq = 0..2;
foreach (var s in seq.ToEnumerable())
{
System.Console.WriteLine(s);
}
// Output: 0, 1
P.S. But be careful with 'indexes from end'. For example, ToEnumerable extension method is not working with var seq = ^2..^0
.
Budda
I am a software developer, here is my hobby: Virtual Football Manager Elita
Updated on February 21, 2020Comments
-
Budda about 4 years
F# has sequences that allows to create sequences:
seq { 0 .. 10 }
Create sequence of numbers from 0 to 10.
Is there something similar in C#?
-
Anthony Pegram over 13 yearsNote: This creates a sequence starting at 0 with 10 items (ending at 9). If you want 0 through 10, the second parameter would be 11. And if you need an actual array and not
IEnumerable<int>
, include a call.ToArray()
. -
Zimano about 4 yearsI really like this but it also feels a bit hacky at the same time!
-
Zimano about 4 yearslol :-) It's just a great creative use of the indexer overload!
-
ruffin almost 4 yearsBy "more complicated" do you mean just "where you have begin and end handy instead of the number of elements"? Otherwise I'm missing your meaning. 🤔
-
Aman over 3 yearsI believe I was considering
OddSequence
EvenSequence
or other custom ranges.if (++n1 % 2 == 0) yield return n1
, for example. It's been a few days ;) -
ruffin over 3 yearsHa, yeah, one or two days I suppose. Or a few thousand. ;^)
-
Matt Baran almost 3 yearsI feel like doing
Enumerable.Range(0, 12).Select( i => "Minute:" + i*5 )
is more readable.