Dictionary赋初值写法有两种:
var dict = new Dictionary<string, string>()
{
["name"] = "Tom",
["address"] = "sz"
};
或`
var secDict = new Dictionary<string, string>()
{
{"name", "Tom"},
{"address", "sz"}
};
下面展示了遍历key或值,和取某一个key值的方法:
//Dictionary赋初值方式
var dict = new Dictionary<string, string>()
{
["name"] = "Tom",
["address"] = "sz"
};
var secDict = new Dictionary<string, string>()
{
{"name", "Tom"},
{"address", "sz"}
};
//下标方式取值,输出所有key和值
Console.WriteLine("1.--------");
foreach (var key in dict.Keys)
{
Console.WriteLine(key + ":" + dict[key]);
}
//遍历值,输出所有值
Console.WriteLine("2.--------");
foreach (var val in dict.Values)
{
Console.WriteLine(val);
}
//kv方式取key和值,输出所有key和值
Console.WriteLine("3.--------");
foreach (KeyValuePair<string, string> kv in dict)
{
Console.WriteLine(kv.Key + ":" + kv.Value);
}
//输出第1个key和值
Console.WriteLine("4.--------");
var first = dict.FirstOrDefault();
Console.WriteLine(first.Key + ":" + first.Value);
//输出第2个key和值
Console.WriteLine("5.--------");
var ele = dict.ElementAt(1);
Console.WriteLine(ele.Key + ":" + ele.Value);
Console.ReadLine();
结果:
1.--------
name:Tom
address:sz
2.--------
Tom
sz
3.--------
name:Tom
address:sz
4.--------
name:Tom
5.--------
address:sz