1、初始化集合
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 };
2、 添加元素
racers.Add(new Racer(24, "Michael", "Schumacher", "Germany", 91)); racers.Add(new Racer(27, "Mika", "Hakkinen", "Finland", 20)); racers.AddRange(new Racer[] { new Racer(14, "Niki", "Lauda", "Austria", 25), new Racer(21, "Alain", "Prost", "France", 51)});
3、插入元素
racers.Insert(3,new Racer(5,"Phil","Hill","USA",3));
方法InsertRange()提供了插入大量元素的功能。
4、 访问元素
list接口类都提供一个索引器,可通过 racers[2] 索引访问的形式获取元素, 也可以通过 for、foreach 循环的方式进行获取。
5、删除元素
racers.RemoveAt(3); 通过索引进行删除,
int index=3;int count=5;
racers.RemoveRange(index,count);从第index位置元素开始删除, 删除count个元素。
6、搜索
racers.FindIndex(p=>p.FirstName=="Phil");
7、排序
racers.Sort((t, p) => t.Wins.CompareTo(p.Wins));
8、类型转换
List<Person> lis= racers.ConvertAll<Person>(p => new Person(p.FirstName + "" + p.LastName));
9、只读集合
racers.AsReadOnly();