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);
                    }
                }
  • 相关阅读:
    Eclipse中显示行号
    PeerSim中一些自己的理解
    迄今为止看过的书籍
    Java程序跨平台运行
    Linux下在PeerSim中运行Chord源代码
    在Eclipse中运行PeerSim的例子
    Ubuntu下安装Java
    Eclipse中自动调整代码
    Eclipse中Outline里各种图标的含义
    Java是如何运行的
  • 原文地址:https://www.cnblogs.com/codeface/p/5897348.html
Copyright © 2011-2022 走看看