zoukankan      html  css  js  c++  java
  • List<> 集合 删除指定行

      不多说,直接上代码

     public class Name
        {
            public string NameInfo { get; set; }
        }

      删除值为Name2的行

     static void Main(string[] args)
            {
                string[] s = new string[2];
                List<Name> nList = new List<Name>();
                for (int i = 0; i < 5; i++)
                {
                    Name n = new Name()
                    {
                        NameInfo = "Name" + i
                    };
    
                    nList.Add(n);
                }
     
                Console.WriteLine();
                var someOne = "Name2";
    
                for (int i = 0; i < nList.Count; i++)
                {
                    if (someOne == nList[i].NameInfo)
                    {
                        nList.RemoveAt(i);
                        //输出下一个参数
                        Console.WriteLine(nList[++i].NameInfo);
                    }
                }   
            
    for (int i =0; i<nList.Count; i++) { Console.Write(nList[i].NameInfo + " "); } Console.ReadKey(); }

      仔细的同学会发现一个错误:Name2在nList<Name>是第3个即nList[2],删除之后下一个参数应该是nList[3] Name3,但是最后程序结果是Name4。

      原因:当前元素被删除之后,后面的元素会自动前移一位.也就是删除Name2后nList[2]就变成Name3。

      改进:逆反循环,for循环从后开始往前循环

         for (int i = nList.Count - 1; i >= 0; i--)
                {
                    if (someOne == nList[i].NameInfo)
                    {
                        nList.RemoveAt(i);
                        //输出下一个参数
                        Console.WriteLine(nList[--i].NameInfo);
                    }
                }
  • 相关阅读:
    mysql安装遇到的坑
    git pull 、git fetch、 git clone
    MD markdown入门
    Libevent:8Bufferevents高级主题
    Libevent:6辅助函数以及类型
    Libevent:5events相关
    Libevent:4event loop
    Libevent:3创建event_base
    Libevent:2设置
    Libevent:1前言
  • 原文地址:https://www.cnblogs.com/codeface/p/5897348.html
Copyright © 2011-2022 走看看