List 遍历删除 从零开始 牙牙学语

写代码经常铭记性能效率,所以,从我每次写 遍历,就清楚要这么写

        static void Main(string[] args)
        {
            List<int> a = new List<int>();
            a.Add(1);
            a.Add(2);
            a.Add(3);
            a.Add(4);
            a.Add(5);
            a.Add(6);

            int count = a.Count;
            for (int i = 0; i < count; i++)
            {
                if (a[i]==3)
                {
                    a.Remove(a[i]);
                 
                }
                Console.WriteLine(a[i]);
            }
            Console.ReadLine();
        }

这样的遍历,count 一次算好,遍历时候就不需要每次计算。不过以上这样写,代码是错误的。

list 删除,会自动改变 count长度,但count 固定,就会报错。

所以。。。回忆起当初 第一次写代码的状态。程序完美通过。

   static void Main(string[] args)
        {
            List<int> a = new List<int>();
            a.Add(1);
            a.Add(2);
            a.Add(3);
            a.Add(4);
            a.Add(5);
            a.Add(6);


            for (int i = 0; i < a.Count; i++)
            {
                if (a[i]==3)
                {
                    a.Remove(a[i]);
                 
                }
                Console.WriteLine(a[i]);
            }
            Console.ReadLine();
        }
原文地址:https://www.cnblogs.com/big-zhou/p/11612884.html