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

时间:2014-01-31 06:31:42

标签: c# asp.net list generics

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

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

但是此代码从位置1移除项目,但不从3移除。如何从两个位置删除?请帮我。提前谢谢。

2 个答案:

答案 0 :(得分:4)

使用List<T>.RemoveAll Method

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

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

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

答案 1 :(得分:0)

建议,您也可以使用Where来获得结果

List<string> postalCodes = new List<string> { "A1B", "A2B", "A3B", "A2B" };
string currentPostalCode = "A2B";
postalCodes = postalCodes.Where(f => f != currentPostalCode).ToList<string>();