字典(Dictionary)泛型的练习
class DictionaryExample
{
public static void Main()
{
Dictionary<int, string> dicStudents = new Dictionary<int, string>();
dicStudents.Add(1, "李刚");
dicStudents.Add(2, "黄何军");
dicStudents.Add(3, "方如波");
dicStudents.Add(4, "陆前霖");
dicStudents.Add(5, "蓝斌");
for (int i = 1; i <= dicStudents.Count;i++ )
{
Console.WriteLine(dicStudents[i]);
}
//利用Linq语句排序
var s=from item in dicStudents
where item.Key==4
orderby item.Value
select item;
foreach (var t in s)
{
Console.WriteLine("key="+t.Key+" value="+t.Value);
}
/*使用KeyValuePair进行输出*/
foreach (KeyValuePair<int,string>t in s)
{
Console.WriteLine("key=" + t.Key + " value=" + t.Value);
}
Console.Read();
}
private Dictionary<string, int> students = new Dictionary<string, int>();
public void AddStudent(string name, int ID)
{
students.Add(name, ID);
}
public int GetStudentIDByName(string name)
{
return students[name];
}
public void DelStudent(string name)
{
students.Remove(name);
}
void DisplayStudents()
{
foreach (KeyValuePair<string,int> s in students)
{
Console.WriteLine("key=" + s.Key + " vale=" + s.Value);
}
}
public static void Main()
{
DictionaryExample de = new DictionaryExample();
de.AddStudent("甘全福", 26);
de.AddStudent("李刚", 5);
de.AddStudent("方如波", 7);
Console.WriteLine("添加的学生后的学生信息如下:");
de.DisplayStudents();
de.DelStudent("甘全福");
Console.WriteLine("删除后的学生信息如下:");
de.DisplayStudents();
Console.WriteLine("根据姓名返回学生的ID");
Console.WriteLine("ID=" + de.GetStudentIDByName("李刚") + "by name");
Console.Read();
}
}
}