(2)C# ArrayList,List<T>

tech2025-02-14  7

using System; using System.Collections.Generic; //List所在名称空间 using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; //ArrayList 所在名称空间 namespace CSharpTest { class Program { class student { public student(string _name, int _id) { name = _name; id = _id; } public string name; public int id; } private static void printMsg(object[] obj) { student stu = (student)obj[4]; Console.Write("name:" + stu.name + "\nid:" + stu.id); } static void Main(string[] args) { //ArrayList 类:使用大小可按需动态增加的数组。相当与c++容器一类的东西 //操作过程涉及到装箱,拆箱 ,不用 ArrayList arrL = new ArrayList(); arrL.Add(7); arrL.Add(new student("su", 2)); //可以混合添加元素,应用中尽量不要这样去使用 int[] arr = new int[] { 1, 2, 3, 4 }; arrL.AddRange(arr); //添加一段元素,数组元素 foreach(var value in arrL) { Console.WriteLine(value); } arrL.Remove(2); //移除元素 arrL.RemoveAt(2);//移除序号处的元素 arrL.Insert(2, 77);//在序号为2的地方插入元素77 //List 跟C++的list 很接近了 List<int> list = new List<int>(); list.Add(4); list.Remove(4);//移除这个元素 list.Add(5); list.RemoveAt(0);//移除下标为0处的元素 list.Add(6); list.Clear(); int[] arr1 = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; list.AddRange(arr1); list.Sort();//排序 list.Sum();//求和 list.Reverse();//翻转 list.Reverse();//翻转 if (list.Contains(6)) //是否包括有某元素 { } int index = list.BinarySearch(100);//找到返回索引值,找不到返回-10,默认需要数组从小到大排好序 } } }

 

最新回复(0)