C#数组、集合
数组是一种可以存放同一类型数据集合的数据结构,属于引用类型。
初始化:
声明一个大小为5的Int型的集合
int [] numbers=new int[5];

int [] numbers =new int[5]{1,2,3,4,5};
或者
int [] numbers ={1,2,3,4,5}

访问:
使用整形参数的索引器访问数组中的每一个元素(索引值从0开始)
int [] numbers ={1,2,3,4,5}
Console.WriteLine(numbers[0]); //1
Console.WriteLine(numbers[4]); //5
泛型 集合
list<T>
使用时根据实际分配内存
class Program
{
static void Main(string[] args)
{
Student student1 = new Student(1001, "李1");
Student student2 = new Student(1002, "李2");
Student student3 = new Student(1003, "李3");
Student student4 = new Student(1004, "李4");
List<Student> stuList = new List<Student>();
//集合初始化器
//List<Student> stuList1 = new List<Student>() { student1, student2, student3, student4 };
stuList.Add(student1);
stuList.Add(student2);
stuList.Add(student3);
stuList.Add(student4);
stuList.Add(new Student() { StudentName = "李四", StudentId = 1006 });
//错误的类型
//stuList.Add(new Teacher() { teacherId = 1005, teacherName = "" });
Console.WriteLine("元素总数:{0}",stuList.Count);
stuList.RemoveAt(0);
stuList.Insert(0, new Student(1005, "张三"));
foreach (Student item in stuList)
{
Console.WriteLine(item.StudentName+"\t"+item.StudentId);
}
Console.ReadLine();
}
}
class Student
{
public Student()
{ }
public Student(int stuId,string stuName)
{
StudentId = stuId;
StudentName = stuName;
}
public int StudentId { get; set; }
public string StudentName { get; set; }
public int Age { get; set; }
}
class Teacher
{
public int teacherId { get; set; }
public string teacherName { get; set; }
}
Dictionary<K,V> 键值对
//创建Dictionary集合
Dictionary<string, Student> stus = new Dictionary<string, Student>();
stus.Add("李1", student1);
stus.Add("李2", student2);
stus.Add("李3", student3);
stus.Add("李4", student4);
Console.WriteLine(stus["李3"].StudentName+ "\t\t" +stus["李2"].StudentId);
Console.WriteLine("************************************");
foreach (string key in stus.Keys)
{
Console.WriteLine(key);
}
Console.WriteLine("************************************");
foreach (Student value in stus.Values)
{
Console.WriteLine(value.StudentName+"\t"+value.StudentId);
}
Console.ReadLine();
集合的排序
list.sort();
比较器
Class: IComparer<T>
浙公网安备 33010602011771号