Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

.net - Generating numbers list in C#

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...