List和Dictionary是泛型集合,ArrayList和Hashtable是非泛型集合
//List
List<int> allSore = new List<int>();
List<Myclass> allSore1 = new List<Myclass>();
allSore.Add(80);
allSore.Add(90);
allSore.Add(110);
allSore.Add(105);
//List的访问
int v = allSore[0];
Console.WriteLine("下标0的元素为:"+ v);
//List中插入元素
allSore.Insert(1, 85);
//移除,从前到后遇到的第一个86删除
allSore.Remove(85);
//通过下标删除
//allSore.RemoveAt(1);
//简单排序
allSore.Sort();
//集合的遍历
foreach (int d in allSore)
{
Console.WriteLine(d);
}
//计算运行时间
Console.WriteLine("值类型");
Stopwatch stopwatch1 = new Stopwatch();
Stopwatch stopwatch2 = new Stopwatch();
Stopwatch stopwatch3 = new Stopwatch();
Stopwatch stopwatch4 = new Stopwatch();
stopwatch1.Start();
for (int i = 0; i < 10000; i++)
{
allSore.Add(2);
}
stopwatch1.Stop();
Console.WriteLine(stopwatch1.Elapsed);
stopwatch2.Start();
for (int i = 0; i < 10000; i++)
{
arrList.Add(2);
}
stopwatch2.Stop();
Console.WriteLine(stopwatch2.Elapsed);
//Console.ReadKey(); //按任意字符继续
Console.WriteLine("引用类型");
stopwatch3.Start();
for (int i = 0; i < 10000; i++)
{
allSore1.Add(new Myclass());
}
stopwatch3.Stop();
Console.WriteLine(stopwatch3.Elapsed);
stopwatch4.Start();
for (int i = 0; i < 10000; i++)
{
arrList1.Add(new Myclass());
}
stopwatch4.Stop();
Console.WriteLine(stopwatch4.Elapsed);
//ArrayList
ArrayList arrList = new ArrayList();
ArrayList arrList1 = new ArrayList();
arrList.Add(33);
arrList.Add(6);
arrList.Add("jack");
arrList.Add("JK");
object v1 = arrList[0];
object v2 = arrList[2];
Console.WriteLine(v1);
ArrayList arylist = new ArrayList();
arylist.Add("JK");
arylist.Add('h');
arylist.Add(45);
arylist.Add(14.7f);
bool c = arylist.Contains("JK");
Console.WriteLine(c);
Console.WriteLine(arylist.Capacity);
arylist.Insert(2,33);
Console.WriteLine(arylist.IndexOf(45));
arylist.Remove(45);
arylist.Reverse();
foreach (object o in arylist)
{
Console.Write(" "+o);
}
//arylist.Clear();
//字典
Dictionary<string, int> stu = new Dictionary<string, int>();
stu.Add("JK1", 96);
stu.Add("JK2", 84);
stu.Add("JK3", 88);
stu.Add("JK4", 88);
//字典的访问
foreach (var item in stu)
{
Console.WriteLine(item);
//Console.WriteLine(item.Key);
}
//JK的得分 取值方式
int score = stu["JK1"];
Console.WriteLine(score);
stu["JK2"] = 80;
Console.WriteLine(stu["JK2"]);
if (stu.ContainsKey("jack"))
{
Console.WriteLine("jack存在");
}
else
{
Console.WriteLine("不存在");
}
Console.WriteLine(stu["jack"]); //运行报错
//添加元素时
stu.Add("JK2", 91); //不能重复添加同一键,key唯一
List<Student> student = new List<Student>();
#region 输入四个学生的成绩
List<Student> student = new List<Student>();
while (true)
{
Student stud = new Student();
Console.WriteLine("请输入学号");
stud.ID =Console.ReadLine();
Console.WriteLine("输入姓名");
stud.name = Console.ReadLine();
Console.WriteLine("请输入成绩");
stud.grade = float.Parse(Console.ReadLine());
student.Add(stud);
Console.WriteLine("空格键结束录入");
ConsoleKeyInfo key = Console.ReadKey();
if (key.Key == ConsoleKey.Spacebar)
{
break;
}
}
student.Sort();
#endregion