[예]
Dictionary<string, string> dict = new Dictionary<string, string>
{
{ "key1", "value1" }
};
우연히 발견한 사실입니다
dictionary의 Value 변경이 foreach를 통해서는 할 수 없다네요.
[에러나는 경우 1] <------- 원래 foreach는 안된다고 함
foreach(KeyValuePair<string, string> items in dict){
if(dict[items.Key] == "key1"){
dict[items.Key] ="kkkkkkkkkkkk";
}
Console.Write(items.Key + " " + items.Value);
}
[에러나는 경우 2] <----- for문은 시도 할 수 있다고 함
for (int index = 0; index <dict.Count; index++)
{
KeyValuePair<int, string> month = dict.ElementAt(index);
Console.Write(month.Key + " " + month.Value);
}
질문 1.에러나는 경우 1처럼 foreach로 변경이 안되는 다른 Collection.Generics에는 없는지요?
질문2. 에러나는 경우 2의 경우는 dict.ElementAt에서 에러가 나는 데 왜 그런가요?
+++성공 1 +++
string key = "key1";
bool keyExists = dict.ContainsKey(key);
if (keyExists) {
dict[key] = "newvalue";
}
[최초 등록일: ]
[최종 수정일: 3/30/2023]