Give this a try:
foreach(var key in d.Keys.ToArray())
{
d[key] = "absent";
}
The .ToArray()
is needed because the foreach
loop will throw an error before the second iteration if you try to iterate on d.Keys
directly.
문제
I have a Dictionary. I've used a loop to add elements in the dictionary and changed them over time through code. How can I revert the elements back to their initial value? My code:
//for adding to the dictionary
Dictionary<string, string> D = new Dictionary<string, string>();
for(i=0; i<DataSet1.Tables[0].Rows.Count; i++)
{
row = DataSet1.Tables[0].Rows[i];
id[i]=row["UserID"].ToString();
D.Add(id[i], "absent");
}
//for reassigning back to absent
for(int i =0; i<D.Count; i++) D[i.ToString()]="absent";
My reassigning loop instead of reassign seems to just add new elements. Initialy counted about 1000 and after the reassign loop it's about 3000.. P.S. Using c# Please help
해결책 2
Give this a try:
foreach(var key in d.Keys.ToArray())
{
d[key] = "absent";
}
The .ToArray()
is needed because the foreach
loop will throw an error before the second iteration if you try to iterate on d.Keys
directly.
다른 팁
You can enumerate keys of your dictionary and set entries values:
foreach(string key in D.Keys.ToArray())
D[key] = "absent";
Also creation of dictionary can be simplified to (with help of Linq to DataSet):
var D = DataSet1.Tables[0].AsEnumerable()
.ToDictionary(r => r.Field<string>("UserID"),
r => "absent");