zoukankan      html  css  js  c++  java
  • 循环list删除自己本身的集合

    • 如果从头到尾正序遍历删除的话,有些符合删除条件的元素会成为漏网之鱼;
      正序删除举例:
       List<string> tempList = new List<string>() { "a","b","b","c" };
    
       for (int i = 0; i < tempList.Count; i++)
       {
           if (tempList[i] == "b")
           {
               tempList.Remove(tempList[i]);
           }
       }
    
       tempList.ForEach(p => {
           Console.Write(p+",");
       });
    

    控制台输出结果:a,b,b,c
    有两个2没有删除掉;
    这是因为当i=1时,满足条件执行删除操作,会移除第一个b,接着第二个b会前移到第一个b的位置,即游标1对应的是第二个b。
    接着遍历i=2,也就跳过第二个b。

    • 用for倒序遍历删除,从尾到头
       List<string> tempList = new List<string>() { "a","b","b","c" };
    
       for (int i = tempList.Count-1; i>=0; i--)
       {
           if (tempList[i] == "b")
           {
               tempList.Remove(tempList[i]);
           }
       }
    
       tempList.ForEach(p => {
           Console.Write(p+",");
       });
    

    控制台输出结果:a,c,
    这次删除了所有的b;

    使用递归,每次删除以后都从新foreach,就不存在这个问题了;

        static void Main(string[] args)
        {
            List<string> tempList = new List<string>() { "a","b","b","c" };
            RemoveTest(tempList);
    
            tempList.ForEach(p => {
                Console.Write(p+",");
            });
        }
        static void RemoveTest(List<string> list)
        {
            foreach (var item in list)
            {
                if (item == "b")
                {
                    list.Remove(item);
                    RemoveTest(list);
                    return;
                }
            }
        }
  • 相关阅读:
    webpack
    一 java包管理
    docker 保存本地容器 推送镜像
    virtualBox 安装linux系统 网络设置小记
    centos6.5编译安装nginx[整理二]
    go基本使用
    docker基础命令使用
    centos 安装docker
    docker 删除容器及镜像
    PHP Thread Safe和Non ThreadSafe
  • 原文地址:https://www.cnblogs.com/ZK1115655608/p/12516865.html
Copyright © 2011-2022 走看看