下面是用KeyValuePair遍历Dictionary的例子:
public void test()
{
Dictionary<string,modelTest> tDictonart=new Dictionary<string,modelTest>();
modelTest t1=new modelTest(25,"张三");
modelTest t2=new modelTest(24,"李四");
modelTest t3=new modelTest(25,"王五");
tDictonart.Add("张三",t1);
tDictonart.Add("李四",t2);
tDictonart.Add("王五",t3);
foreach(KeyValuePair<string,modelTest> tKeyValuePair in tDictonart)
{
MessageBox.Show(tKeyValuePair.Value.Name+":"+ tKeyValuePair.Value.Age+";");
}
foreach(KeyValuePair<string,modelTest> tKeyValuePair in tDictonart)
{
if(tKeyValuePair.Value.Name=="张三")
{
MessageBox.Show("张三:"+tKeyValuePair.Value.Age);
}
}
}
public class modelTest
{
public int Age {get;set; }
public string Name { get; set; }
public modelTest(int age,string name)
{
Age=age;
Name=name;
}
}