【问题标题】:Deleting all same values from Generic List从通用列表中删除所有相同的值
【发布时间】:2014-01-31 06:31:42
【问题描述】:

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

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

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

【问题讨论】:

    标签: c# asp.net list generics


    【解决方案1】:

    使用List&lt;T&gt;.RemoveAll Method:

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

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

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

    【讨论】:

      【解决方案2】:

      一个建议,你也可以使用Where得到你喜欢的结果

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

      【讨论】:

        猜你喜欢
        • 2017-11-07
        • 2015-05-04
        • 1970-01-01
        • 2013-05-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-12
        相关资源
        最近更新 更多