zoukankan      html  css  js  c++  java
  • C#中删除集合中符合条件的元素以及需注意属相

    如果用foreach,会造成被遍历的集合更改后带来异常问题。

    此时,用for循环可有效的解决这个问题。

    for(int i=0;i<List.Count;i++)
    {
     if(条件是真)
     {
     List.Remove(List[i]);
     i--;
     }
    }
    

      上面我们看到,当我们进行Remove操作后,元素的个数减少了,并且移除的是当前元素,所以需要对“”当前”(后一个元素自动补充到当前来)元素重新判断操作。

      下面这段代码是我实际应用中遇到的问题,i--直接导致是否产生bug

                //移旧
                for (int i = 0; i < gParent.Children.Count; i++)
                {
                    if (gParent.Children[i].GetType().Name == "CapImagePanel")
                    {
                        gParent.Children.RemoveAt(i);
                        i--;
                    }
                }

    或者,再用另外的一个List集合存储要删除的对象。

    List<T> newlists=new List<T>();
    foreach(T t in List)
    {
     lists.add(t);
    }
    foreach(T t in newlists)
    {
     List.Remove(t);
    }
    

      

  • 相关阅读:
    「CodeForces
    「POJ
    「CodeForces
    「CodeForces
    【CodeForces 717C】Potions Homework
    【CodeForces 730H】Car Repair Shop
    【CodeForces 730H】Delete Them
    【Gym 100947I】What a Mess
    j
    PDE工具箱的简单使用
  • 原文地址:https://www.cnblogs.com/xietianjiao/p/7263584.html
Copyright © 2011-2022 走看看