Home > Back-end >  Removing an array of int from a list of type int array
Removing an array of int from a list of type int array

Time:09-29

I intend to have a field of type List<int[]> that holds some int array (used in Unity to record some grid positions), looks roughly like:

{
 {0, 0},
 {0, 1},
 {0, 2}
}

But when I try to remove elements from this list, it seems to be having some difficulty doing so:

int[] target = new int[] {0, 0}; 
// Simplified, in the actual code I have to do some calculations. 
// But during debug, I confirmed that the same array I want to remove 
// is in the intArrayList

intArrayList.Remove(target);

// {0, 0} seems to be still here

Is that supposed to happen? If so, how can I fix that?

CodePudding user response:

The problem is that you are deleting a different instance of the same list. Since C# array uses the default equality checker, the instance needs to be the same in order for the other array to get removed.

A quick fix is to write your own method that searches the list for the appropriate array first, and then removing the item at that index:

var target =  new int[] {0, 0}; 
var indexToRemove = intArrayList.FindIndex(a => a.SequenceEqual(target));
if (indexToRemove >= 0) {
    intArrayList.RemoveAt(indexToRemove);
}

A good fix is to stop using the "naked" array: wrap it into your own class with an appropriate comparison semantic, and use that class instead. This would make your code more readable, give you more control over what goes into the array, and let you protect the array from writing if necessary. It will also let you use the original removal code, which is a small bonus on top of the other great things you are going to get for writing a meaningful wrapper on top of the array.

CodePudding user response:

You are trying to remove the array by ref and most likely your intention is to remove it by value.

this should work:

intArrayList.RemoveAll(p => p[0] == 0 && p[1] == 0);

Another option is to use records instead of int[2] arrays since they have built-in implementation of value equality

record GridPosition(int X, int Y);
//...
List<GridPosition> intArrayList = new();
intArrayList.Add(new GridPosition(0, 0));
intArrayList.Add(new GridPosition(1, 0));

var target = new GridPosition(0, 0);
intArrayList.Remove(target);
Assert.AreEqual(1, intArrayList.Count);
  • Related