How can I remove int [] from the list <int []>?
I am new to using List as arrays in C #. So I am facing a problem while using it.
I am trying to remove int[]
(integer array) from List<int[]>
using Remove
, but could not remove int[]
from List<int[]>
.
here is the code:
List<int[]> trash = new List<int[]>()
{
new int[] {0,1},
new int[] {1,0},
new int[] {1,1}
};
int[] t1 = {0,1};
trash.Remove(t1);
Is this just a mistake? Or does he not recognize int[]
?
source to share
The problem is that every array type is a reference type and List
removes elements based on equality, where equality for reference types defaults to reference equality. This means that you need to delete the same array as in the list.
Below, for example, works great:
int[] t1 = {0,1};
List<int[]> trash = new List<int[]>()
{
t1,
new int[] {1,0},
new int[] {1,1}
};
trash.Remove(t1);
source to share
If you want to remove all lists with the same content (in the same order) as the target list, you can do so using List.RemoveAll()
along with Linq SequenceEqual()
:
List<int[]> trash = new List<int[]>
{
new [] {0, 1},
new [] {1, 0},
new [] {1, 1}
};
int[] t1 = {0, 1};
trash.RemoveAll(element => element.SequenceEqual(t1));
Console.WriteLine(trash.Count); // Prints 2
It is very slow. Better to use an index if you can.
source to share
Mistake. The array list uses reference data. so use the removeAt List method like below:
List<int[]> trash = new List<int[]>()
{
new int[] {0,1},
new int[] {1,0},
new int[] {1,1}
};
trash.RemoveAt(0);
With RemoveAt, you need to pass in the index of the integer array that you want to remove from the list.
source to share
This is simply because you are trying to delete a new item.
Its address link is different from the object that is already in the list. This is why it is not removed.
Int is a value type .. AND Int [] is a reference type ..
So when you do it with an Int list
List<int> trash = new List<int>(){ 1, 13, 5 };
int t1 = 13;
trash.Remove(t1);//it will removed
But for Int []
List<int[]> trash = new List<int[]>()
{
new int[] {0,1},
new int[] {1,0},
new int[] {1,1}
};
var t1 = {0,1};
trash.Remove(t1);//t1 will not removed because "t1" address reference is different than the "new int[] {0,1}" item that is in list.
To delete -
trash.Remove(trash.Find(a => a.SequenceEqual(t1)));
SequenceEqual () Determines whether two sequences are equal by comparing elements using the default equality matcher for their type.
source to share
If you want to remove the exact sequence, but you have no way of removing the exact object (the sequence comes out of a different place), you can search for the correct sequence using a lambda expression or anonymous method:
List<int[]> trash = new List<int[]>
{
new [] {0, 1},
new [] {1, 0},
new [] {1, 1}
};
int[] t1 = { 0, 1 };
//using anonymous method
trash.RemoveAll(delegate(int[] element) { return element.SequenceEqual(t1); });
//using lambda expression
trash.RemoveAll(element => element.SequenceEqual(t1));
source to share