C# 在 .NET 中填充整数列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 10:01:59  来源:igfitidea点击:

Populating a list of integers in .NET

提问by Glenn Slaven

I need a list of integers from 1 to x where x is set by the user. I could build it with a for loop eg assuming x is an integer set previously:

我需要一个从 1 到 x 的整数列表,其中 x 由用户设置。我可以用 for 循环构建它,例如假设 x 是之前设置的整数:

List<int> iList = new List<int>();
for (int i = 1; i <= x; i++)
{
    iList.Add(i);
}

This seems dumb, surely there's a more elegant way to do this, something like the PHP range method

这似乎很愚蠢,当然有一种更优雅的方法可以做到这一点,例如PHP range 方法

采纳答案by jfs

If you're using .Net 3.5, Enumerable.Rangeis what you need.

如果您使用 .Net 3.5,Enumerable.Range就是您所需要的。

Generates a sequence of integral numbers within a specified range.

生成指定范围内的整数序列。

回答by aku

LINQ to the rescue:

LINQ 来救援:

// Adding value to existing list
var list = new List<int>();
list.AddRange(Enumerable.Range(1, x));

// Creating new list
var list = Enumerable.Range(1, x).ToList();

See Generation Operatorson LINQ 101

请参阅LINQ 101上的生成运算符

回答by Samuel Hyman

I'm one of many who has bloggedabout a ruby-esque Toextension method that you can write if you're using C#3.0:

如果您使用 C#3.0,我是许多写过关于 ruby​​-esque To扩展方法的博客的人之一:


public static class IntegerExtensions
{
    public static IEnumerable<int> To(this int first, int last)
    {
        for (int i = first; i <= last; i++)
{ yield return i; } } }

Then you can create your list of integers like this

然后你可以像这样创建整数列表

List<int> = first.To(last).ToList();

or

或者

List<int> = 1.To(x).ToList();

回答by Gaspare Bonventre

Here is a short method that returns a List of integers.

这是一个返回整数列表的简短方法。

    public static List<int> MakeSequence(int startingValue, int sequenceLength)
    {
        return Enumerable.Range(startingValue, sequenceLength).ToList<int>();
    }