2012-03-29 144 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"); 
相关问题