2014-11-04 52 views
0

我想申報的INT rows陣列具有可變大小(X)和初始化所有值爲1。對於我用這個時刻:灌裝int數組在聲明

int[] rows = new int[X]; 
for (int i = 0; i < rows.Length; i++) 
{ 
    rows[i] = 1; 
} 

是有什麼更快/更短的方式來做到這一點fill(1)int[] rows = new int[X] {1};

回答

1

LINQ:

int[] rows = Enumerable.Repeat(element:1, count: X).ToArray();// named parameter - X 
                   // doesn't tell anything 
+1

作爲埃裏克利珀筆記,這樣做是[比簡單地寫一個循環慢的數十倍(http://stackoverflow.com/questions/1897555/what-is-the-等價於memset-in-c#comment1804854_1897564)(它[實際上是](http://stackoverflow.com/a/1051227/11683))。 – GSerg 2014-11-04 09:58:34