C# 如何用另一个数组创建和初始化一个数组?
要使用另一个数组创建和初始化数组,我当前执行以下操作:C# 如何用另一个数组创建和初始化一个数组?,c#,arrays,C#,Arrays,要使用另一个数组创建和初始化数组,我当前执行以下操作: void Foo( int[] a ) { int[] b = new int[ a.Length ]; for ( int i = 0; i < a.Length; ++i ) b[ i ] = a[ i ]; // Other code ... } void Foo(int[]a) { int[]b=新的int[a.长度]; 对于(int i=0;i
void Foo( int[] a )
{
int[] b = new int[ a.Length ];
for ( int i = 0; i < a.Length; ++i )
b[ i ] = a[ i ];
// Other code ...
}
void Foo(int[]a)
{
int[]b=新的int[a.长度];
对于(int i=0;i
在C#中是否有一种更短或更惯用的方法来实现这一点
如果这可以在一个语句中完成,就像在C++中一样,那就太好了:
vector<int> b( a );
向量b(a);
如果这不能在一个语句中完成,我将使用我得到的:-)我喜欢使用LINQ来实现这一点:
int[] b = a.ToArray();
也就是说,如果在紧密循环中使用Array.Copy,那么它确实具有更好的性能,等等:
int[] b = new int[a.Length];
Array.Copy(a, b, a.Length);
编辑: 如果这可以在一个语句中完成,就像在C++中一样,那就太好了:
vector<int> b( a );
载体b(a)
这种情况的C版本是:
List<int> b = new List<int>(a);
List b=新列表(a);
List
是C#的等价物std::vector
。可用于任何IEnumerable
,包括另一个列表
、数组(T[]
)等。用于复制数组
int[] source = new int[5];
int[] target = new int[5];
Array.Copy(source, target, 5);
还可以尝试默认的
Clone()
函数,该函数是从IClonable
接口实现的
int[] b = a.Clone() as int[];
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");
const int arraylelength=100000;
常数int numberCopies=1000;
var a=新的整数[arrayLength];
var b=新的整数[arrayLength];
var stopwatch=新秒表();
对于(变量i=0;i
您可以通过创建新的空数组或使用给定数组轻松实现这一点
int[] arr = { 1, 2, 0, 3, 4, 5, 0, 6, 0, 7, 8, 9, 0 };
int[] newArray = new int[arr.Length];
Array.Copy(arr, newArray, arr.Length);
foreach (var item in newArray)
{
if(item != 0)
Console.WriteLine(item);
}
这个解决方案决不是最快的,也不是最优雅的,但是如果您需要从原始数组中跳过一些元素,或者转换它们,那么您可以使用Linq来实现这一点
var sourceArray = new int[] {1,2,3,4,5,6,7,8,9 };
var targetArray = sourceArray.Select(s => s).ToArray();
// targetArray now contains 1,2,3,4,5,6,7,8,9
我承认,这看起来有点愚蠢,除非在复制过程中需要执行某种操作
var sourceArray = new int[] {1,2,3,4,5,6,7,8,9 };
var targetArray = sourceArray.Skip(1).Take(3).Select(s => s*s+4).ToArray();
// targetArray now contains 8,13,20
你不能只使用<代码>数组吗?拷贝< /C> >应该是一个直接复制所有内存的方法……在C++中,我的问题与我在C++中寻找的等价向量B(a)有点不同。