Remove element of a regular array

2018-12-31 20:22发布

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.

标签: c# .net arrays
13条回答
何处买醉
2楼-- · 2018-12-31 20:55

This is a way to delete an array element, as of .Net 3.5, without copying to another array - using the same array instance with Array.Resize<T>:

public static void RemoveAt<T>(ref T[] arr, int index)
{
    for (int a = index; a < arr.Length - 1; a++)
    {
        // moving elements downwards, to fill the gap at [index]
        arr[a] = arr[a + 1];
    }
    // finally, let's decrement Array's size by one
    Array.Resize(ref arr, arr.Length - 1);
}
查看更多
与君花间醉酒
3楼-- · 2018-12-31 20:58

The nature of arrays is that their length is immutable. You can't add or delete any of the array items.

You will have to create a new array that is one element shorter and copy the old items to the new array, excluding the element you want to delete.

So it is probably better to use a List instead of an array.

查看更多
美炸的是我
4楼-- · 2018-12-31 20:59

In a normal array you have to shuffle down all the array entries above 2 and then resize it using the Resize method. You might be better off using an ArrayList.

查看更多
美炸的是我
5楼-- · 2018-12-31 21:00

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<TElement>(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<TElement>(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<TElement>(params TElement[] Elements)
    {
        return Elements ?? new TElement[0];
    }

    public static void Remove<TElement>(ref TElement[] Source, params TElement[] Elements)
    {
        foreach (var i in Elements)
            RemoveAt(ref Source, Source.IndexOf(i));
    }

    public static void RemoveAt<TElement>(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<string>(ref myArray, "A", "B", "C");

Or

Arr.Add<string>(ref myArray, anotherArray);
查看更多
长期被迫恋爱
6楼-- · 2018-12-31 21:01
    private int[] removeFromArray(int[] array, int id)
    {
        int difference = 0, currentValue=0;
        //get new Array length
        for (int i=0; i<array.Length; i++)
        {
            if (array[i]==id)
            {
                difference += 1;
            }
        }
        //create new array
        int[] newArray = new int[array.Length-difference];
        for (int i = 0; i < array.Length; i++ )
        {
            if (array[i] != id)
            {
                newArray[currentValue] = array[i];
                currentValue += 1;
            }
        }

        return newArray;
    }
查看更多
浮光初槿花落
7楼-- · 2018-12-31 21:06

I use this method for removing an element from an object array. In my situation, my arrays are small in length. So if you have large arrays you may need another solution.

private int[] RemoveIndices(int[] IndicesArray, int RemoveAt)
{
    int[] newIndicesArray = new int[IndicesArray.Length - 1];

    int i = 0;
    int j = 0;
    while (i < IndicesArray.Length)
    {
        if (i != RemoveAt)
        {
            newIndicesArray[j] = IndicesArray[i];
            j++;
        }

        i++;
    }

    return newIndicesArray;
}
查看更多
登录 后发表回答