Remove element of a regular array

前端 未结 15 2486
野性不改
野性不改 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:22

    If you don't want to use List:

    var foos = new List(array);
    foos.RemoveAt(index);
    return foos.ToArray();
    

    You could try this extension method that I haven't actually tested:

    public static T[] RemoveAt(this T[] source, int index)
    {
        T[] dest = new T[source.Length - 1];
        if( index > 0 )
            Array.Copy(source, 0, dest, 0, index);
    
        if( index < source.Length - 1 )
            Array.Copy(source, index + 1, dest, index, source.Length - index - 1);
    
        return dest;
    }
    

    And use it like:

    Foo[] bar = GetFoos();
    bar = bar.RemoveAt(2);
    

提交回复
热议问题