自动初始化 C# 列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1104457/
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-06 08:21:16  来源:igfitidea点击:

Auto-initializing C# lists

c#.netlistcollections

提问by JasCav

I am creating a new C# List (List<double>). Is there a way, other than to do a loop over the list, to initialize all the starting values to 0?

我正在创建一个新的 C# 列表 ( List<double>)。除了对列表进行循环之外,有没有办法将所有起始值初始化为 0?

采纳答案by Michael Meadows

In addition to the functional solutions provided (using the static methods on the Enumerableclass), you can pass an array of doubles in the constructor.

除了提供的函数式解决方案(使用Enumerable类上的静态方法)之外,您还可以double在构造函数中传递一个s数组。

var tenDoubles = new List<double>(new double[10]);

This works because the default value of an doubleis already 0, and probably performs slightly better.

这是有效的,因为 an 的默认值double已经是 0,并且性能可能稍好一些。

回答by Jhonny D. Cano -Leftware-

You can use the initializer:

您可以使用初始化程序:

var listInt = new List<int> {4, 5, 6, 7};
var listString = new List<string> {"string1", "hello", "world"};
var listCustomObjects = new List<Animal> {new Cat(), new Dog(), new Horse()};

So you could be using this:

所以你可以使用这个:

var listInt = new List<double> {0.0, 0.0, 0.0, 0.0};

Otherwise, using the default constructor, the List will be empty.

否则,使用默认构造函数,列表将为空。

回答by SLaks

Use this code:

使用此代码:

Enumerable.Repeat(0d, 25).ToList();
new List<double>(new double[25]);     //Array elements default to 0

回答by Colin

For more complex types:

对于更复杂的类型:

List<Customer> listOfCustomers =
        new List<Customer> {
            { Id = 1, Name="Dave", City="Sarasota" },
            { Id = 2, Name="John", City="Tampa" },
            { Id = 3, Name="Abe", City="Miami" }
        };

from here: David Hayden's Blog

从这里:大卫海登的博客

回答by jason

One possibility is to use Enumerable.Range:

一种可能性是使用Enumerable.Range

int capacity;
var list = Enumerable.Range(0, capacity).Select(i => 0d).ToList();

Another is:

另一个是:

int capacity;
var list = new List<double>(new double[capacity]);

回答by Daniel

A bit late, but maybe still of interest: Using LINQ, try

有点晚了,但也许仍然感兴趣:使用 LINQ,尝试

var initializedList = new double[10].ToList()

var initializedList = new double[10].ToList()

...hopefully avoiding copying the list (that's up to LINQ now).

...希望避免复制列表(现在由 LINQ 决定)。

This should be a comment to Michael Meadows' answer, but I'm lacking reputation.

这应该是对迈克尔梅多斯回答的评论,但我缺乏声誉。