Wojciech Szabowicz
Wojciech Szabowicz

Reputation: 4198

Remove an array from list

Hello I am having a simple question. When I try to remove array from list of arrays like:

var mock = new byte[] { 0x00, 0x01, 0x02 };
var list = new List<byte[]> { new byte[] { 0x00, 0x01, 0x02 } };
list.Remove(mock);

Value is still in array, what could be the cause?

Upvotes: 1

Views: 185

Answers (5)

Gilad Green
Gilad Green

Reputation: 37299

It doesn't work for you because int[] is a reference type and not value type so basically mock and list[0] are not the same.

What you can do is to use RemoveAll to specify a predicate that will use SequenceEquals to find all those inner arrays that all the items are equal:

var mock = new byte[] { 0x00, 0x01, 0x02 };
var list = new List<byte[]> 
{ 
    new byte[] { 0x00, 0x01, 0x02 }, 
    new byte[] { 0x03, 0x04, 0x05 } 
};

list.RemoveAll(item => mock.SequenceEqual(item));

The SequenceEqual will check that all the items of the 2 arrays are Equal - here too it matters if it is value or reference type, but in your case with value types it will work. If the inner items were a reference type you'd have to override the Equals and GetHashCode or provide a custom IEqualityComparer<T>


If you do want to use Remove, now after we understood that we have to specify the same object (and it is a reference type) then use FirstOrDefault and then on that result use the Remove:

var result = list.FirstOrDefault(item => mock.SequenceEqual(item));
if(result != null)
{
    list.Remove(result);
}

Upvotes: 4

BOBIN JOSEPH
BOBIN JOSEPH

Reputation: 1022

You're comparing two object references, and they are not the same. You need to compare the byte array contents. You have to use SequenceEqual in c# (3.5 orhigher)

bool equal = Array1.SequenceEqual(Array2);

Its requires Linq implementation.

list.RemoveAll(x=> mock.SequenceEqual(x));

Please refer the following MSDN link MSDN - SequenceEqual

Upvotes: 1

Nico
Nico

Reputation: 3542

You are removing the array by reference. If you want to remove an array that is equal, you have to check for sequence similarity:

list.RemoveAll(e => e.SequenceEqual(mock));

Upvotes: 1

Pikoh
Pikoh

Reputation: 7703

That's because the object you are removing is not the same as the one in the list, although the values are the same. Try this and you´ll see it works fine:

var mock = new byte[] { 0x00, 0x01, 0x02 };
var list = new List<byte[]> { {mock} };
list.Remove(mock);

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190943

You have 2 arrays with the same value. .Remove goes by reference, not value.

var mock = new byte[] { 0x00, 0x01, 0x02 };
var mock2 = new byte[] { 0x00, 0x01, 0x02 };
mock === mock2; // false

Upvotes: 3

Related Questions