Remove element of a regular array

前端 未结 15 2489
野性不改
野性不改 2020-11-22 10:06

I have an array of Foo objects. How do I remove the second element of the array?

I need something similar to RemoveAt() but for a regular array.

15条回答
  •  悲&欢浪女
    2020-11-22 10:48

    First step
    You need to convert the array into a list, you could write an extension method like this

    // Convert An array of string  to a list of string
    public static List ConnvertArrayToList(this string [] array) {
    
        // DECLARE a list of string and add all element of the array into it
    
        List myList = new List();
        foreach( string s in array){
            myList.Add(s);
        }
        return myList;
    } 
    

    Second step
    Write an extension method to convert back the list into an array

    // convert a list of string to an array 
    public static string[] ConvertListToArray(this List list) {
    
        string[] array = new string[list.Capacity];
        array = list.Select(i => i.ToString()).ToArray();
        return array;
    }
    

    Last steps
    Write your final method, but remember to remove the element at index before converting back to an array like the code show

    public static string[] removeAt(string[] array, int index) {
    
        List myList = array.ConnvertArrayToList();
        myList.RemoveAt(index);
        return myList.ConvertListToArray();
    } 
    

    examples codes could be find on my blog, keep tracking.

提交回复
热议问题