《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()方法。