zoukankan      html  css  js  c++  java
  • 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();
            }
  • 相关阅读:
    MySQL教程22-字符串类型
    MySQL教程21-日期和时间类型
    MySQL教程20-小数类型
    MySQL教程19-整数类型
    MySQL教程18-数据类型简介
    ActiveMQ_topic
    ActiveMQ_消费者编码
    ActiveMQ_生产者编码
    ActiveMQ介绍
    管理docker容器
  • 原文地址:https://www.cnblogs.com/big-zhou/p/11612884.html
Copyright © 2011-2022 走看看