How do I quicky fill an array with a specific value?

匿名 (未验证) 提交于 2019-12-03 02:15:02

问题:

Array.Clear() fills the arrays with the default value (zero for integers), I would like to fill it using -1 for example.

Thanks.

回答1:

The other way is:

int[] arr =  Enumerable.Repeat(-1, 10).ToArray(); Console.WriteLine(string.Join(",",arr)); 


回答2:

I am not aware of such a method. You could write one yourself, though:

public static void Init<T>(this T[] array, T value) {     for(int i=0; i < array.Length; ++i)     {         array[i] = value;     } } 

You can call it like this:

int[] myArray = new int[5]; myArray.Init(-1); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!