字典---Dictionary<TKey,TValue>
=================================================EmployeeID.cs(学生编号类)
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceConsoleApplication7{//作为键的类型必须要重写GetHashCode()publicclassEmployeeID:IEquatable<EmployeeID>{publicstringID{get;privateset;}publicEmployeeID(strings){ID=s;}publicoverrideboolEquals(objectobj){if(obj==null)thrownewArgumentException("对象不能为空");returnthis.Equals(objasEmployeeID);}publicoverrideintGetHashCode(){return1;}publicboolEquals(EmployeeIDother){returnthis.ID==other.ID;}}}
=================================================Student.cs(学生类)
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceConsoleApplication7{publicclassStudent{publicstringName{get;privateset;}publicEmployeeIDID{get;privateset;}publicStudent(EmployeeIDid,stringname){this.Name=name;this.ID=id;}}}
=================================================主程序
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceConsoleApplication7{classProgram{staticvoidMain(string[]args){Dictionary<EmployeeID,Student>d=newDictionary<EmployeeID,Student>();varID1=newEmployeeID("Z001");varStu1=newStudent(ID1,"张飞");d.Add(ID1,Stu1);varID2=newEmployeeID("Z002");varStu2=newStudent(ID2,"关羽");d.Add(ID2,Stu2);varID3=newEmployeeID("Z003");varStu3=newStudent(ID3,"曹操");d.Add(ID3,Stu3);varID4=newEmployeeID("Z004");varStu4=newStudent(ID4,"赵云");d.Add(ID4,Stu4);varID5=newEmployeeID("Z005");varStu5=newStudent(ID5,"马超");d.Add(ID5,Stu5);while(true){stringstr=Console.ReadLine();if(str.ToLower()=="exit")return;Students;EmployeeIDei=null;ei=newEmployeeID(str);if(!d.TryGetValue(ei,outs))//判断是否存在键对应的相关的值{Console.WriteLine("没有找到该学生");}else{Console.WriteLine(d[ei].Name);}}}}}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。