使用系统;
使用 System.Collections.Generic;
DictionaryDemo 类
{
静态无效主(字符串[]参数)
{
字典演示001();
Console.ReadLine();
字典演示002();
Console.ReadLine();
字典演示003();
Console.ReadLine();
}
/// <摘要>
/// 一般用法
/// </摘要>
静态无效 DictionaryDemo001()
{
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "111");
dict.Add(2, "222");
//判断是否存在相应的key并显示
if (dict.ContainsKey(2))
{
Console.WriteLine(dict[2]);
}
//遍历Keys C#
foreach(dict.Keys 中的 var 项目)
{
Console.WriteLine("密钥:{0}", item);
}
//遍历值
foreach(dict.Values 中的 var 项目)
{
Console.WriteLine("值:{0}", item);
}
//遍历整个字典
foreach(字典中的var项目)
{
Console.WriteLine("键:{0} 值:{1}", item.Key, item.Value);
}
}
/// <摘要>
/// 参数为其他类型
/// </摘要>
静态无效 DictionaryDemo002()
{
Dictionary<string, string[]> dict = new Dictionary<string, string[]>();
dict.Add("1", "1,11,111".Split(','));
dict.Add("2", "2,22,222".Split(','));
Console.WriteLine(dict["2"][2]);
}
/// <摘要>
/// 调用自定义类
/// </摘要>
静态无效 DictionaryDemo003()
{
Dictionary<int, yongfa365> dict = new Dictionary<int, yongfa365>();
for (int i = 0; i < 10; i++)
{
yongfa365 y = 新的 yongfa365();
y.用户代码 = i;
y.UserName = "
www.knowsky.com " + i.ToString();
字典.Add(i, y);
}
foreach(字典中的var项目)
{
Console.WriteLine("{0}一:{1}用户名:{2}", item.Key, item.Value.UserCode, item.Value.UserName);
}
}
}
永发365班
{
公共 int 用户代码 { 获取;放; }
公共字符串用户名{获取;放; }
}
http://www.cnblogs.com/kingfly/archive/2010/01/18/1650578.html