Remove element of a regular array

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

    Here's a small collection of helper methods I produced based on some of the existing answers. It utilizes both extensions and static methods with reference parameters for maximum idealness:

    public static class Arr
    {
        public static int IndexOf(this TElement[] Source, TElement Element)
        {
            for (var i = 0; i < Source.Length; i++)
            {
                if (Source[i].Equals(Element))
                    return i;
            }
    
            return -1;
        }
    
        public static TElement[] Add(ref TElement[] Source, params TElement[] Elements)
        {
            var OldLength = Source.Length;
            Array.Resize(ref Source, OldLength + Elements.Length);
    
            for (int j = 0, Count = Elements.Length; j < Count; j++)
                Source[OldLength + j] = Elements[j];
    
            return Source;
        }
    
        public static TElement[] New(params TElement[] Elements)
        {
            return Elements ?? new TElement[0];
        }
    
        public static void Remove(ref TElement[] Source, params TElement[] Elements)
        {
            foreach (var i in Elements)
                RemoveAt(ref Source, Source.IndexOf(i));
        }
    
        public static void RemoveAt(ref TElement[] Source, int Index)
        {
            var Result = new TElement[Source.Length - 1];
    
            if (Index > 0)
                Array.Copy(Source, 0, Result, 0, Index);
    
            if (Index < Source.Length - 1)
                Array.Copy(Source, Index + 1, Result, Index, Source.Length - Index - 1);
    
            Source = Result;
        }
    }
    

    Performance wise, it is decent, but it could probably be improved. Remove relies on IndexOf and a new array is created for each element you wish to remove by calling RemoveAt.

    IndexOf is the only extension method as it does not need to return the original array. New accepts multiple elements of some type to produce a new array of said type. All other methods must accept the original array as a reference so there is no need to assign the result afterward as that happens internally already.

    I would've defined a Merge method for merging two arrays; however, that can already be accomplished with Add method by passing in an actual array versus multiple, individual elements. Therefore, Add may be used in the following two ways to join two sets of elements:

    Arr.Add(ref myArray, "A", "B", "C");
    

    Or

    Arr.Add(ref myArray, anotherArray);
    

提交回复
热议问题