在C#中,遍历字典的方法有以下几种:
Dictionary<string, int> dict = new Dictionary<string, int>();
foreach (KeyValuePair<string, int> kvp in dict)
{
string key = kvp.Key;
int value = kvp.Value;
Console.WriteLine("Key: {0}, Value: {1}", key, value);
}
Dictionary<string, int> dict = new Dictionary<string, int>();
foreach (string key in dict.Keys)
{
int value = dict[key];
Console.WriteLine("Key: {0}, Value: {1}", key, value);
}
Dictionary<string, int> dict = new Dictionary<string, int>();
foreach (int value in dict.Values)
{
Console.WriteLine("Value: {0}", value);
}
Dictionary<string, int> dict = new Dictionary<string, int>();
var query = from kvp in dict
select kvp;
foreach (var kvp in query)
{
string key = kvp.Key;
int value = kvp.Value;
Console.WriteLine("Key: {0}, Value: {1}", key, value);
}
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: C#中怎么定义和使用属性