Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Remove a list from a "jagged" list

Tags:

c#

list

I'm trying to remove a List<int> from a List<List<int>>, I've looked everywhere and haven't found a solution.

Here's what I've tried so far:

List<List<int>> my2DList = ... ;  // this is where I assign my 2D list
my2DList.Remove(new List<int>( ... ));

But my2DList's length stays the same. What should I do?

like image 803
kiyah Avatar asked Dec 18 '25 23:12

kiyah


1 Answers

The problem is that List<int> doesn't override Equals/GetHashCode, so your new list is never equal to the existing one. (Basically, it will be comparing references rather than contents.)

Three options:

  • Find the exact list you want to remove, and pass that reference to Remove
  • Find the index of the list you want to remove, and pass that to RemoveAt
  • Create a predicate and use RemoveAll

An example of the last one:

List<int> listToRemove = new List<int> { ... };
my2DList.RemoveAll(x => x.SequenceEqual(listToRemove));
like image 87
Jon Skeet Avatar answered Dec 21 '25 00:12

Jon Skeet