user2123959
user2123959

Reputation:

Remove item from List<string[]> or get index of any item at any position

I am trying to remove item from List<string[]> but remove property is not working but if I use RemoveAt(0) (any int hardcoded value) then it's working ... What could be problem. Can anyone help me?

Here is my code...

List<string[]> ipcol1 = new List<string[]>();
ipcol1.Add(new string[] { "test1" });
ipcol1.Add(new string[] { "test2" });
ipcol1.Add(new string[] { "test3" });
ipcol1.Add(new string[] { "test4" });
ipcol1.Remove(new string[] { "test1" });

int i = ipcol1.IndexOf(new string[] { "test4" });
ipcol1.RemoveAt(i);

Or if I am trying to take index of perticular item then it's giving me (-1) as result ... If I can get index of that problem then my problem can resolve... Please help me.

Upvotes: 1

Views: 1405

Answers (2)

IMK
IMK

Reputation: 718

The arrays are reference types. The below code fails because you are comparing the references of two separate instances.

ipcol1.Remove(new string[] { "test1" });

You can use SequenceEqual to compare collections.

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

You have to use SequenceEqual when comparing arrays:

  List<string[]> ipcol1 = new List<string[]>();
  ipcol1.Add(new string[] { "test1" });
  ipcol1.Add(new string[] { "test2" });
  ipcol1.Add(new string[] { "test3" });
  ipcol1.Add(new string[] { "test4" });

  ipcol1.RemoveAll(array => array.SequenceEqual(new string[] { "test1" }));

Or (in case you want to remove any record which contains "test1" somewhere in array):

  ipcol1.RemoveAll(array => array.Any(item => item == "test1")));

The reason is that two arrays are equal if they have the same reference :

  string[] array1 = new string[0];
  string[] array2 = array1;
  string[] array3 = new string[0];

  // "Yes" - array1 and array2 reference to the instance
  Console.WriteLine((array1 == array2) ? "Yes" : "No");
  // "No" - array1 and array3 are references to different instances
  Console.WriteLine((array1 == array3) ? "Yes" : "No");

  // "Yes" - array1 and array3 are equal sequences
  Console.WriteLine((array1.SequenceEqual(array3)) ? "Yes" : "No");

Upvotes: 5

Related Questions