可能重复:
自动初始化C#列表
我有一个具有一定容量的整数列表,我希望在声明时自动填充.
List<int> x = new List<int>(10);
Run Code Online (Sandbox Code Playgroud)
有没有更简单的方法来填充此列表10个具有int的默认值而不是循环并添加项目的整数?
Jon*_*eet 122
好吧,你可以让LINQ为你做循环:
List<int> x = Enumerable.Repeat(value, count).ToList();
Run Code Online (Sandbox Code Playgroud)
目前还不清楚"默认值"是指0还是自定义默认值.
你可以通过创建一个数组来提高效率(执行时间;内存更差):
List<int> x = new List<int>(new int[count]);
Run Code Online (Sandbox Code Playgroud)
这将从数组块中复制到列表中,这可能比所需的循环更有效ToList.
Tim*_*son 10
int defaultValue = 0;
return Enumerable.Repeat(defaultValue, 10).ToList();
Run Code Online (Sandbox Code Playgroud)
如果你有一个固定长度列表,并且你希望所有元素都具有默认值,那么也许你应该只使用一个数组?
int[] x = new int[10];
Run Code Online (Sandbox Code Playgroud)
或者,这可能是自定义扩展方法的粘性场所
public static void Fill<T>(this ICollection<T> lst, int num)
{
Fill(lst, default(T), num);
}
public static void Fill<T>(this ICollection<T> lst, T val, int num)
{
lst.Clear();
for(int i = 0; i < num; i++)
lst.Add(val);
}
Run Code Online (Sandbox Code Playgroud)
然后你甚至可以为List类添加一个特殊的重载来填充容量
public static void Fill<T>(this List<T> lst, T val)
{
Fill(lst, val, lst.Capacity);
}
public static void Fill<T>(this List<T> lst)
{
Fill(lst, default(T), lst.Capacity);
}
Run Code Online (Sandbox Code Playgroud)
那么你可以说
List<int> x = new List(10).Fill();
Run Code Online (Sandbox Code Playgroud)
是的
int[] arr = new int[10];
List<int> list = new List<int>(arr);
Run Code Online (Sandbox Code Playgroud)