12.泛型集合Dictionary
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _2.泛型集合Dictionary
{
class Program
{
static void Main(string[] args)
{
//创建几个学员对象
Student objstu1 = new Student(1001, "小王");
Student objstu2 = new Student(1002, "校长");
Student objstu3 = new Student(1003, "小李");
Student objstu4 = new Student(1004, "小刘");
//创建Dictionary泛型集合
Dictionary<int, Student> stus = new Dictionary<int, Student>();
stus.Add(1, objstu1);
stus.Add(2, objstu2);
stus.Add(3, objstu3);
stus.Add(4, objstu4);
//取出元素
int strId = stus[1].StudentId;
string strName = stus[1].StudentName;
//遍历
//方法1
foreach (int key in stus.Keys)
{
Console.WriteLine(key);
}
//方法2
foreach (Student value in stus.Values)
{
Console.WriteLine(value.StudentName+"\t"+value.StudentId+"\t"+value.Age);
}
Console.Read();
}
}
class Student
{
public Student()
{
}
/// <summary>
/// 带有参数的构造函数
/// </summary>
/// <param name="stuId"></param>
/// <param name="stuNmae"></param>
public Student(int stuId, string stuNmae)
{
this.StudentId = stuId;
this.StudentName = stuNmae;
}
public int StudentId { get; set; }
public string StudentName { get; set; }
public int Age { get; set; }
}
}