填单子<&诠释GT;使用默认值? [英] Fill List<int> with default values?

查看:72
本文介绍了填单子<&诠释GT;使用默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
自动初始化C#列表

我有一个整数列表有一定的容量,我想声明的时候自动填写。

I have a list of integers that has a certain capacity that I would like to automatically fill when declared.

List<int> x = new List<int>(10);



有没有更简单的方式来填补这个名单有10个整数具有默认值的int,而?不是通过循环和增加的项目

Is there an easier way to fill this list with 10 ints that have the default value for an int rather than looping through and adding the items?

推荐答案

好了,你可以问LINQ为你做的循环:

Well, you can ask LINQ to do the looping for you:

List<int> x = Enumerable.Repeat(value, count).ToList();



目前还不清楚是否是默认值是指0或自定义默认值。

It's unclear whether by "default value" you mean 0 or a custom default value.

您可以让这个会更有效(在执行时,它在内存中更差)通过创建一个数组:

You can make this slightly more efficient (in execution time; it's worse in memory) by creating an array:

List<int> x = new List<int>(new int[count]);

这将执行从阵列的块拷贝到列表,这可能会比更有效循环要求了ToList

That will do a block copy from the array into the list, which will probably be more efficient than the looping required by ToList.

这篇关于填单子&LT;&诠释GT;使用默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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