Simple Sequence Generation?

11,929

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;
Share:
11,929
abelenky
Author by

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, 2022

Comments

  • abelenky
    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
    abelenky almost 15 years
    You are indeed correct. I didn't read closely enough. Thanks for setting me straight.
  • Robert Cartaino
    Robert Cartaino almost 15 years
    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.
  • Daniel Earwicker
    Daniel Earwicker almost 15 years
    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.