生成号码列表在C# [英] Generating numbers list in C#

查看:135
本文介绍了生成号码列表在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?

我使用.NET 3.5

I am using .NET 3.5

推荐答案

这可能会是一个快一点 - 它肯定更简单:

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

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

你绝对需要它作为一个数组有关系吗?如果你只需要遍历它,你可以只使用<一href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.range.aspx"><$c$c>Enumerable.Range直接获得一个的IEnumerable&LT; INT&GT; 这从来不需要实际持有内存中的所有号码在同一时间

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.

这篇关于生成号码列表在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆