C# Dictionary 应用

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);
}
上一篇:小丁带你走进git的世界三-撤销修改


下一篇:惊呆了!Java程序员最常犯的错竟然是这10个