Adding elements to a C# array

前端 未结 10 416
野趣味
野趣味 2021-01-11 19:29

I would like to programmatically add or remove some elements to a string array in C#, but still keeping the items I had before, a bit like the VB function ReDim Preserve.

10条回答
  •  北荒
    北荒 (楼主)
    2021-01-11 19:58

    The obvious suggestion would be to use a List instead, which you will have already read from the other answers. This is definitely the best way in a real development scenario.

    Of course, I want to make things more interesting (my day that is), so I will answer your question directly.

    Here are a couple of functions that will Add and Remove elements from a 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;
    }
    

提交回复
热议问题