将元素添加到C#数组

Cip*_*ppo 10 c#

我想以编程方式在C#中添加或删除一些字符串数组中的元素,但仍然保留我以前的项目,有点像VB函数ReDim Preserve.

Pao*_*lla 11

如果你真的不会(或不能)使用泛型集合而不是你的数组,那么Array.Resize是c#版本的redim preserve:

var  oldA = new [] {1,2,3,4};
Array.Resize(ref oldA,10);
foreach(var i in oldA) Console.WriteLine(i); //1 2 3 4 0 0 0 0 0 0
Run Code Online (Sandbox Code Playgroud)


mus*_*fan 10

显而易见的建议是使用a List<string>,你已经从其他答案中读过了.这绝对是真实开发场景中的最佳方式.

当然,我想让事情变得更有趣(我的那一天),所以我会直接回答你的问题.

以下是一些将添加和删除元素的函数string[]...

string[] Add(string[] array, string newValue){
    int newLength = array.Length + 1;

    string[] result = new string[newLength];

    for(int i = 0; i < array.Length; i++)
        result[i] = array[i];

    result[newLength -1] = newValue;

    return result;
}

string[] RemoveAt(string[] array, int index){
    int newLength = array.Length - 1;

    if(newLength < 1)
    {
        return array;//probably want to do some better logic for removing the last element
    }

    //this would also be a good time to check for "index out of bounds" and throw an exception or handle some other way

    string[] result = new string[newLength];
    int newCounter = 0;
    for(int i = 0; i < array.Length; i++)
    {
        if(i == index)//it is assumed at this point i will match index once only
        {
            continue;
        }
        result[newCounter] = array[i];
        newCounter++;
    }  

    return result;
}
Run Code Online (Sandbox Code Playgroud)


M.B*_*ock 6

由于数组实现,IEnumerable<T>您可以使用Concat:

string[] strArr = { "foo", "bar" };
strArr = strArr.Concat(new string[] { "something", "new" });
Run Code Online (Sandbox Code Playgroud)

或者更合适的是使用支持内联操作的集合类型.


Ode*_*ded 5

不要使用数组 - 使用List<T>允许动态添加项的通用.

如果这不是一个选项,您可以使用Array.CopyArray.CopyTo将数组复制到更大的数组中.