我有一个包含一些字符串值的通用列表。有时值会重复。而且我必须从列表集合中删除特定值。我尝试了以下代码。
List<string> postalCodes = new List<string> { "A1B", "A2B", "A3B","A2B" };
string currentPostalCode = "A2B";
postalCodes.RemoveAt(postalCodes.IndexOf(currentPostalCode));
但是这段代码从位置 1 中删除项目,而不是从位置 3 中删除项目。如何从两个位置删除?请帮帮我。提前致谢。
请您参考如下方法:
postalCodes.RemoveAll(c => c == currentPostalCode);
如果你想使用RemoveAt你必须循环执行:
int index;
while((index = postalCodes.IndexOf(currentPostalCode)) != -1)
{
postalCodes.RemoveAt(index);
}
