2012-03-29 67 views
9

要創建和初始化另一個陣列我現在做這樣的數組:如何用另一個數組創建和初始化一個數組?

void Foo(int[] a) 
{ 
    int[] b = new int[ a.Length ]; 
    for (int i = 0; i < a.Length; ++i) 
     b[ i ] = a[ i ]; 

    // Other code ... 
} 

有沒有在C#這樣做的更短或更地道的方式?

這將是巨大的,如果這可以在一個單獨的語句來完成,就像在C++:

vector<int> b(a); 

如果不能在一個語句來完成,我會採取什麼我得到:-)

+2

不能你只需要使用'Array.Copy'? – 2012-03-29 00:04:16

+0

應該是一種直接複製所有內存的方法...在C++中http://stackoverflow.com/questions/3902215/using-memcpy-to-copy-a-range-of-elements-from-an-array – 2012-03-29 00:05:14

+0

HTTP://計算器。COM /問題/ 5655553 /什麼最最有效的路到副本元素-的-AC鋒利多維-ARR – 2012-03-29 00:08:11

回答

12

我喜歡使用LINQ此:

int[] b = a.ToArray(); 

話雖這麼說,Array.Copy確實有更好的表現,這是否會在緊密循環使用等:

int[] b = new int[a.Length]; 
Array.Copy(a, b, a.Length); 

編輯:

這將是巨大的,如果這可以在單個語句來完成,如在C++:

矢量b(a)的

這樣做的C#版本是:

List<int> b = new List<int>(a); 

List<T>是C#的相當於std::vector<T>。該constructor above適用於任何IEnumerable<T>,包括另一List<T>,數組(T[])等

+0

+1等效 - 我從來沒有考慮過LINQ這一點。好的解決方案 – 2012-03-29 00:07:12

6

使用Array.Copy複製一個數組

 int[] source = new int[5]; 
    int[] target = new int[5]; 
    Array.Copy(source, target, 5); 
1

也可以嘗試這從IClonable接口實現的默認Clone()功能。

int[] b = a.Clone() as int[]; 
1

的clone()和ToArray的()在語法上是不錯的,因爲你並不需要預先分配目的數組,但在性能方面,Array.Copy()是最快的方法(見下文警告)。

Array.Copy()如此之快的原因是它沒有分配任何內存。但是,如果您需要將陣列每次都複製到新的內存區域,那麼Array.Copy()不再是最快的方法。

這裏是我的性能測試結果:

Copy: 0 ms 
Copy (with allocation): 449 ms 
Clone: 323 ms 
ToArray: 344 ms 

這裏是我使用的代碼:

const int arrayLength = 100000; 
const int numberCopies = 1000; 
var a = new int[arrayLength]; 
var b = new int[arrayLength]; 

var stopwatch = new Stopwatch(); 
for (var i = 0; i < numberCopies; i++) { 
    Array.Copy(a, b, arrayLength); 
} 
Console.WriteLine($"Copy: {stopwatch.ElapsedMilliseconds} ms"); 

stopwatch.Restart(); 
for (var i = 0; i < numberCopies; i++) { 
    var c = new int[arrayLength]; 
    Array.Copy(a, c, arrayLength); 
} 
Console.WriteLine($"Copy (with allocation): {stopwatch.ElapsedMilliseconds} ms"); 

stopwatch.Restart(); 
for (var i = 0; i < numberCopies; i++) { 
    b = (int[]) a.Clone(); 
} 
Console.WriteLine($"Clone: {stopwatch.ElapsedMilliseconds} ms"); 

stopwatch.Restart(); 
for (var i = 0; i < numberCopies; i++) { 
    b = a.ToArray(); 
} 
Console.WriteLine($"ToArray: {stopwatch.ElapsedMilliseconds} ms"); 
相關問題