• 《C#高级编程》读书笔记(七):集合


    1,列表的容量和元素个数

        列表的容量和元素个数是两个概念。使用Capacity属性可以获取和设置集合的容量。集合中的元素个数可用用Count属性读取。

        如果列表的容量不足以容纳要添加的元素,就把集合的大小重新设置为原来的2倍。

                var intList = new List<int>();
                intList.Capacity = 20;
    
                Console.WriteLine(intList.Capacity);//20
                Console.WriteLine(intList.Count);//0
    
                for (int i = 0; i < 30; i++)
                {
                    intList.Add(i);
                }
    
                Console.WriteLine(intList.Capacity);//40
                Console.WriteLine(intList.Count);//30

     2,向集合中添加元素

                var graham = new Racer(7, "Graham", "Hill", "UK", 14);
                var emerson = new Racer(13, "Emerson", "Fittipaldi", "Brazil", 14);
                var mario = new Racer(16, "Mario", "Andretti", "USA", 12);
                
                //用集合初始化设定项添加
                var racers= new List<Racer>(20) {graham,emerson,mario};
    
                //显示调用Add()方法来添加
                racers.Add(new Racer(24,"Michale","Schumacher","Germany",91));
                racers.Add(new Racer(27,"Mika","Hakkinen","Finland",20));
    
                //使用List<T>类的AddRange()方法
                racers.AddRange(new Racer[]
                {
                    new Racer(14,"Niki","Lauda","Austria",25),
                    new Racer(21,"Alain","Prost","France",51),  
                });
    
                foreach (var racer in racers)
                {
                    Console.WriteLine(racer.ToString());
                }

        List<T>类的ForEach()方法:

    //ForEach方法
    racers.ForEach(r=>Console.WriteLine($"{r:A}"));

        使用Find方法查找单个元素

    racers.Add(new Racer(28,"Shujian","Song","China",90));
                Racer racer1 = racers.Find(r => r.Country == "China");
                Console.WriteLine($"{racer1:A}");

        使用FindAll查询符合条件的集合

                List<Racer> bigWinners = racers.FindAll(r => r.Wins > 20);
                Console.WriteLine("BigWinners:");
                foreach (var bigWinner in bigWinners)
                {
                    Console.WriteLine($"{bigWinner:A}");
                }

     3,字典

         用作字典中键的类型必须重写Object类中的GetHashCode()方法。只要字典里需要确定元素的位置,他就要调用GetHashCode()方法。

         

  • 相关阅读:
    Eclipse快捷键 10个最有用的快捷键
    Eclipse--Web项目中 .classpath、mymetadata、project文件的功用
    java.lang.IllegalStateException:Web app root system property already set to different value 错误原因及解决 Log4j
    验证位置时发生错误:“org.tigris.subversion.javahl.ClientException......
    隐藏控制台黑窗口
    APK伪加密
    格蠹汇编-01-blog
    static_cast、dynamic_cast、const_cast和reinterpret_cast总结
    CONTAINING_RECORD宏
    explicit关键字
  • 原文地址:https://www.cnblogs.com/khjian/p/5650601.html
Copyright © 2020-2023  润新知