Adding elements to a C# array

前端 未结 10 408
野趣味
野趣味 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:42

    Use List<string> instead of string[].

    List allows you to add and remove items with good performance.

    0 讨论(0)
  • 2021-01-11 19:45

    What's abaut this one:

    List<int> tmpList = intArry.ToList(); tmpList.Add(anyInt); intArry = tmpList.ToArray();

    0 讨论(0)
  • 2021-01-11 19:47

    Don't use an array - use a generic List<T> which allows you to add items dynamically.

    If this is not an option, you can use Array.Copy or Array.CopyTo to copy the array into a larger array.

    0 讨论(0)
  • 2021-01-11 19:55

    One liner:

        string[] items = new string[] { "a", "b" };
    
        // this adds "c" to the string array:
        items = new List<string>(items) { "c" }.ToArray();      
    
    0 讨论(0)
  • 2021-01-11 19:56

    You can use a generic collection, like List<>

    List<string> list = new List<string>();
    
    // add
    list.Add("element");
    
    // remove
    list.Remove("element");
    
    0 讨论(0)
  • 2021-01-11 19:58

    The obvious suggestion would be to use a List<string> 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;
    }
    
    0 讨论(0)
提交回复
热议问题