C# 如何通过foreach 修改Dictionary的value

2025-01-07 06:30:23
推荐回答(5个)
回答1:

可以这样做
Dictionary dic = new Dictionary();
dic.Add("key1", "value1");//添加
dic.Add("key2", "value2");//添加
dic["key1"] = "value3";//修改

p.s.
用foreach的话Value 是只读的,要么for循环,要么重新构建new Dictionary();添加不满足条件的就行了

回答2:

Dictionary dic = new Dictionary();
dic.Add(0, 4);
dic.Add(1, 5);
dic.Add(2, 6);
//遍历键
foreach (int i in dic.Keys)
{
Console.WriteLine(dic[i].ToString());
}
//遍历值
foreach (int i in dic.Values)
{
Console.WriteLine(i.ToString());
}

回答3:

Dictionary testMap = new Dictionary();
testMap["1"] = "test1";
testMap["2"] = "test2";
testMap["3"] = "test3";
testMap["4"] = "test4";
testMap["5"] = "test5";
testMap["6"] = "test6";
List> lst = new List>();

foreach (KeyValuePair kv in testMap)
{
string groupCode = kv.Key;
string dateTime = kv.Value;
if (groupCode == "1")
{
lst.Add(kv);

}
}
for (int i = 0; i < lst.Count; i++)
{
testMap.Remove(lst[i].Key);
testMap[lst[i].Key] = "i have modified it";
}

回答4:

dic[KEY]="你需要的值";

回答5:

Dictionary dic = new Dictionary();
foreach (KeyValuePair item in dic)
{
item.Value = "你需要的值";
}