Simple Sequence Generation?
Solution 1
.NET 3,5 has Range
too. It's actually Enumerable.Range
and returns IEnumerable<int>
.
The page you linked to is very much out of date - it's talking about 3 as a "future version" and the Enumerable
static class was called Sequence
at one point prior to release.
If you wanted to implement it yourself in C# 2 or later, it's easy - here's one:
IEnumerable<int> Range(int count)
{
for (int n = 0; n < count; n++)
yield return n;
}
You can easily write other methods that further filter lists:
IEnumerable<int> Double(IEnumerable<int> source)
{
foreach (int n in source)
yield return n * 2;
}
But as you have 3.5, you can use the extension methods in System.Linq.Enumerable
to do this:
var evens = Enumerable.Range(0, someLimit).Select(n => n * 2);
Solution 2
var r = Enumerable.Range( 1, 200 );
Solution 3
Check out System.Linq.Enumerable.Range.
Regarding the second part of your question, what do you mean by "arbitrary lists"? If you can define a function from an int
to the new values, you can use the result of Range with other LINQ methods:
var squares = from i in Enumerable.Range(1, 200)
select i * i;
abelenky
I've worked in C, C++, C#, ASP.net, Python and touched on many other languages. Graduated from MIT in '96 in Computer Science, active in politics. At various times, worked for Microsoft, Tegic, AOL, Melodeo, Sagem-Morpho, and (secret project). Currently a Senior Engineer at Spear Power. DOGE: D5VYb9M5TYmPNR86LNiV1PAjL3JxW3Hyeu
Updated on June 21, 2022Comments
-
abelenky almost 2 years
I'm looking for an ultra-easy way to generate a list of numbers, 1-200. (it can be a List, Array, Enumerable... I don't really care about the specific type)
Apparently .Net 4.0 has a Sequence.Range(min,max) method. But I'm currently on .Net 3.5.
Here is a sample usage, of what I'm after, shown with Sequence.Range.
public void ShowOutput(Sequence.Range(1,200));
For the moment, I need consequitive numbers 1-200. In future iterations, I may need arbitrary lists of numbers, so I'm trying to keep the design flexible.
Perhaps there is a good LINQ solution? Any other ideas?
-
abelenky almost 15 yearsYou are indeed correct. I didn't read closely enough. Thanks for setting me straight.
-
Robert Cartaino almost 15 yearsActually, you implementation isn't correct.
Enumerable.Range()
is in the formRange(int start, int count)
, so your second parameter should be 'count
' and your stop condition should ben < start + count
. -
Daniel Earwicker almost 15 yearsThat's true. I've changed the example to be slightly different anyway (always starting from zero), as you could then use
Select
to add an offset to each item - an example of orthogonality.