Remove element of a regular array

C#.NetArrays

C# Problem Overview


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# Solutions


Solution 1 - C#

If you don't want to use List:

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

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

public static T[] RemoveAt<T>(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);

Solution 2 - C#

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.

Solution 3 - C#

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;
}

Solution 4 - C#

LINQ one-line solution:

myArray = myArray.Where((source, index) => index != 1).ToArray();

The 1 in that example is the index of the element to remove -- in this example, per the original question, the 2nd element (with 1 being the second element in C# zero-based array indexing).

A more complete example:

string[] myArray = { "a", "b", "c", "d", "e" };
int indexToRemove = 1;
myArray = myArray.Where((source, index) => index != indexToRemove).ToArray();

After running that snippet, the value of myArray will be { "a", "c", "d", "e" }.

Solution 5 - C#

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);
}

Solution 6 - C#

Here is an old version I have that works on version 1.0 of the .NET framework and does not need generic types.

public static Array RemoveAt(Array source, int index)
{
    if (source == null)
        throw new ArgumentNullException("source");

    if (0 > index || index >= source.Length)
        throw new ArgumentOutOfRangeException("index", index, "index is outside the bounds of source array");

    Array dest = Array.CreateInstance(source.GetType().GetElementType(), source.Length - 1);
    Array.Copy(source, 0, dest, 0, index);
    Array.Copy(source, index + 1, dest, index, source.Length - index - 1);

    return dest;
}

This is used like this:

class Program
{
    static void Main(string[] args)
    {
        string[] x = new string[20];
        for (int i = 0; i < x.Length; i++)
            x[i] = (i+1).ToString();

        string[] y = (string[])MyArrayFunctions.RemoveAt(x, 3);

        for (int i = 0; i < y.Length; i++)
            Console.WriteLine(y[i]);
    }
}

Solution 7 - C#

Not exactly the way to go about this, but if the situation is trivial and you value your time, you can try this for nullable types.

Foos[index] = null

and later check for null entries in your logic..

Solution 8 - C#

As usual, I'm late to the party...

I'd like to add another option to the nice solutions list already present. =)
I would see this as a good opportunity for Extensions.

Reference: http://msdn.microsoft.com/en-us/library/bb311042.aspx

So, we define some static class and in it, our Method.
After that, we can use our extended method willy-nilly. =)

using System;

namespace FunctionTesting {

	// The class doesn't matter, as long as it's static
	public static class SomeRandomClassWhoseNameDoesntMatter {

		// Here's the actual method that extends arrays
		public static T[] RemoveAt<T>( this T[] oArray, int idx ) {
			T[] nArray = new T[oArray.Length - 1];
			for( int i = 0; i < nArray.Length; ++i ) {
				nArray[i] = ( i < idx ) ? oArray[i] : oArray[i + 1];
			}
			return nArray;
		}
	}
	
	// Sample usage...
	class Program {
		static void Main( string[] args ) {
			string[] myStrArray = { "Zero", "One", "Two", "Three" };
			Console.WriteLine( String.Join( " ", myStrArray ) );
			myStrArray = myStrArray.RemoveAt( 2 );
			Console.WriteLine( String.Join( " ", myStrArray ) );
			/* Output
			 * "Zero One Two Three"
			 * "Zero One Three"
			 */

			int[] myIntArray = { 0, 1, 2, 3 };
			Console.WriteLine( String.Join( " ", myIntArray ) );
			myIntArray = myIntArray.RemoveAt( 2 );
			Console.WriteLine( String.Join( " ", myIntArray ) );
			/* Output
			 * "0 1 2 3"
			 * "0 1 3"
			 */
		}
	}
}

Solution 9 - C#

Try below code:

myArray = myArray.Where(s => (myArray.IndexOf(s) != indexValue)).ToArray();

or

myArray = myArray.Where(s => (s != "not_this")).ToArray();

Solution 10 - C#

Here's how I did it...

	public static ElementDefinitionImpl[] RemoveElementDefAt(
		ElementDefinition[] oldList,
		int removeIndex
	)
	{
		ElementDefinitionImpl[] newElementDefList = new ElementDefinitionImpl[ oldList.Length - 1 ];

		int offset = 0;
		for ( int index = 0; index < oldList.Length; index++ )
		{
			ElementDefinitionImpl elementDef = oldList[ index ] as ElementDefinitionImpl;
			if ( index == removeIndex )
			{
				//	This is the one we want to remove, so we won't copy it.  But 
				//	every subsequent elementDef will by shifted down by one.
				offset = -1;
			}
			else
			{
				newElementDefList[ index + offset ] = elementDef;
			}
		}
		return newElementDefList;
	}

Solution 11 - C#

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.

Solution 12 - C#

    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;
    }

Solution 13 - C#

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);

Solution 14 - C#

I know this article is ten years old and therefore probably dead, but here's what I'd try doing:

Use the IEnumerable.Skip() method, found in System.Linq. It will skip the selected element from the array, and return another copy of the array that only contains everything except the selected object. Then just repeat that for every element you want removed and after that save it to a variable.

For example, if we have an array named "Sample" (of type int[]) with 5 numbers. We want to remove the 2nd one, so trying "Sample.Skip(2);" should return the same array except without the 2nd number.

Solution 15 - C#

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<string> ConnvertArrayToList(this string [] array) {

    // DECLARE a list of string and add all element of the array into it

    List<string> myList = new List<string>();
    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<string> 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<string> myList = array.ConnvertArrayToList();
    myList.RemoveAt(index);
    return myList.ConvertListToArray();
} 

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionleoraView Question on Stackoverflow
Solution 1 - C#Andrew KennanView Answer on Stackoverflow
Solution 2 - C#Sebastian DietzView Answer on Stackoverflow
Solution 3 - C#EdHellyerView Answer on Stackoverflow
Solution 4 - C#Jon SchneiderView Answer on Stackoverflow
Solution 5 - C#infografnetView Answer on Stackoverflow
Solution 6 - C#Martin BrownView Answer on Stackoverflow
Solution 7 - C#nawfalView Answer on Stackoverflow
Solution 8 - C#DuncanView Answer on Stackoverflow
Solution 9 - C#Genci YmeriView Answer on Stackoverflow
Solution 10 - C#Paul MitchellView Answer on Stackoverflow
Solution 11 - C#gkrogersView Answer on Stackoverflow
Solution 12 - C#user2884232View Answer on Stackoverflow
Solution 13 - C#user1618054View Answer on Stackoverflow
Solution 14 - C#commandertunaView Answer on Stackoverflow
Solution 15 - C#Bamara CoulibalyView Answer on Stackoverflow