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 + "\t"); } 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);
                }
            }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM