[英]C# Remove a list from a “jagged” list
I'm trying to remove a List<int>
from a List<List<int>>
, I've looked everywhere and haven't found a solution. 我正在尝试从
List<List<int>>
删除List<int>
,我到处寻找并且没有找到解决方案。
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. 但
my2DList
的长度保持不变。 What should I do? 我该怎么办?
The problem is that List<int>
doesn't override Equals
/ GetHashCode
, so your new list is never equal to the existing one. 问题是
List<int>
不会覆盖Equals
/ GetHashCode
,因此您的新列表永远不会等于现有列表。 (Basically, it will be comparing references rather than contents.) (基本上,它将比较参考而不是内容。)
Three options: 三种选择:
Remove
Remove
RemoveAt
RemoveAt
RemoveAll
RemoveAll
An example of the last one: 最后一个例子:
List<int> listToRemove = new List<int> { ... };
my2DList.RemoveAll(x => x.SequenceEqual(listToRemove));
You need to remove the exact object you want to remove, not a new object (which would be a different object). 您需要删除要删除的确切对象,而不是新对象(这将是一个不同的对象)。 So for example:
例如:
my2DList.Remove(my2DList[3]);
If you do not know the index, or the object, you'd need to iterate over the List to find the correct object. 如果您不知道索引或对象,则需要遍历List以查找正确的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.