Skip to main content
 首页 » 编程设计

c#之从通用列表中删除所有相同的值

2024年02月13日16lhb25

我有一个包含一些字符串值的通用列表。有时值会重复。而且我必须从列表集合中删除特定值。我尝试了以下代码。

List<string> postalCodes = new List<string> { "A1B", "A2B", "A3B","A2B" }; 
     string currentPostalCode = "A2B"; 
     postalCodes.RemoveAt(postalCodes.IndexOf(currentPostalCode)); 

但是这段代码从位置 1 中删除项目,而不是从位置 3 中删除项目。如何从两个位置删除?请帮帮我。提前致谢。

请您参考如下方法:

使用 List<T>.RemoveAll Method :

postalCodes.RemoveAll(c => c == currentPostalCode); 

如果你想使用RemoveAt你必须循环执行:

int index; 
while((index = postalCodes.IndexOf(currentPostalCode)) != -1) 
{ 
    postalCodes.RemoveAt(index); 
}