如何用另一个数组创建和初始化一个数组? [英] How to create and initialize an array with another array?

查看:149
本文介绍了如何用另一个数组创建和初始化一个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要使用另一个数组创建和初始化一个数组,我目前正在这样做:

To create and initialize an array with another array I currently do this:

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#中是否有更短或更惯用的方式?

Is there a shorter or more idiomatic way of doing this in C#?

如果可以在单个语句中完成(例如在C ++中),那就太好了

It will be great if this can be done in a single statement, like in C++:

vector<int> b( a );

如果不能在单个语句中完成此操作,我将采取我得到的:-)

If this cannot be done in a single statement, I will take what I get :-)

推荐答案

我喜欢为此使用LINQ:

I like using LINQ for this:

int[] b = a.ToArray();

话虽如此,如果将其用于紧密循环等情况,Array.Copy确实具有更好的性能:

That being said, Array.Copy does have better performance, if this will be used in a tight loop, etc:

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


如果可以在单个语句中完成(例如在C ++中),那就太好了

It will be great if this can be done in a single statement, like in C++:

向量b(a);

其C#版本为:

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

List<T>是C#的std::vector<T>等效项.上面的构造函数可以与任何IEnumerable<T>,包括另一个List<T> ,数组(T[])等

List<T> is C#'s equivalent to std::vector<T>. The constructor above works with any IEnumerable<T>, including another List<T>, an array (T[]), etc.

这篇关于如何用另一个数组创建和初始化一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆