1、字典定义并添加数据
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("a", "北京");
dic.Add("c", "上海");
dic.Add("b", "广州");
dic.Add("d", "深圳");
2、遍历字典项
foreach (KeyValuePair<string, string> d in dic)
{
Console.WriteLine(d.Key + " " + d.Value);
}
foreach (var itm in dic)
{
Console.WriteLine(itm.Key + " " + itm.Value);
}
foreach (string s in dic.Keys)
{
Console.WriteLine(s + " " + dic[s]);
} foreach (string s in dic.Values)
{
Console.WriteLine(s);
}
3、字典排序并输出
字典排序:List<KeyValuePair<string,string>> list = dic.OrderBy(r => r.Key).ToList<KeyValuePair<string, string>>();
//dic =dic.OrderByDescending(r => r.Key).ToDictionary(r => r.Key, r => r.Value);
foreach (KeyValuePair<string, string> kv in list)
{
Console.WriteLine(kv.Key + " " + kv.Value);
}