tags:

views:

152

answers:

3

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?

+8  A: 

.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);
Daniel Earwicker
You are indeed correct. I didn't read closely enough. Thanks for setting me straight.
abelenky
Actually, you implementation isn't correct. `Enumerable.Range()` is in the form `Range(int start, int count)`, so your second parameter should be '`count`' and your stop condition should be `n < start + count`.
Robert Cartaino
That'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.
Daniel Earwicker
+5  A: 
var r = Enumerable.Range( 1, 200 );
JP Alioto
+3  A: 

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;
dahlbyk