gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:36:35 24 4
gpt4 key购买 nike

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

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);
}

关于c# - 从通用列表中删除所有相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21473868/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com