62

I often need to generate lists of numbers. The intervals can have quite a lot of numbers. I have a method like this:

public static int[] GetNumbers(int start, int end)
{
    List<int> list = new List<int>();
    for (int i = start; i < end; i++)
        list.Add(i);
    return list.ToArray();
}

Is there a way to make it simpler, faster?

I am using .NET 3.5

Robin Hood
  • 633
  • 1
  • 5
  • 8

1 Answers1

151

This would probably be a bit faster - and it's certainly simpler:

int[] values = Enumerable.Range(start, end - start).ToArray();

Do you definitely need it as an array though? If you only need to iterate over it, you could just use Enumerable.Range directly, to get an IEnumerable<int> which never needs to actually hold all the numbers in memory at the same time.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • My thoughts on this, shouldn't you calculate these values during runtime instead of prefilling an array, since they only represent a sequenced value? – Caspar Kleijne Jun 26 '11 at 09:05
  • @Caspar: That's why I mentioned using just `Enumerable.Range`. It really depends on what the OP wants to do with it. For example, he may be passing it to a method that requires a list or array - for example, something to shuffle any array. – Jon Skeet Jun 26 '11 at 09:06
  • how do I generate something like 1, 5, 10, 15, 20? Anything in-built? – Zameer Ansari Aug 23 '15 at 12:38