题
我需要一个名单的整数,从1到x,其中x是用户设置的。我可以建立它为循环例如,假设x是一个整数设定之前:
List<int> iList = new List<int>();
for (int i = 1; i <= x; i++)
{
iList.Add(i);
}
这似乎是愚蠢的,肯定有一个更优雅的方式来做到这一点,喜欢的东西 PHP范围的方法
解决方案
如果你使用。净3.5, 可枚举的。范围 你需要的是什么。
生成的序列整体的 号码在一定的范围。
其他提示
我是一个许多人已经 在博客 关于ruby式 要 扩展方法,可以编写如果你使用C#3.0:
public static class IntegerExtensions
{
public static IEnumerable<int> To(this int first, int last)
{
for (int i = first; i <= last; i++)
{
yield return i;
}
}
}
然后你可以为你整数列表的喜欢这个
List<int> = first.To(last).ToList();
或
List<int> = 1.To(x).ToList();
这里是一个短期的方法,返回一整数。
public static List<int> MakeSequence(int startingValue, int sequenceLength)
{
return Enumerable.Range(startingValue, sequenceLength).ToList<int>();
}
不隶属于 StackOverflow