U3d work log [data structure]

Dictionary

remove dictionary element


1. When the foreach loop traverses the dictionary, the original data dictionary cannot be changed (Remove does not work)
2. Solution

[for循环里面操作] 
for(int i = 0; i < dic.Count; i++)
{
    var tmp = dic.ElementAt(i);//需要添加using System.Linq
    //可直接在循环里面进行删除操作
    dic.Remove(tmp.Key);
}
[foreach记录,再操作]
List<KeyType> keyList = new List<KeyType>();
foreach(var pair in dic)
{
    if(...)
    {
        keyList.Add(pair.Key);//记录需要处理的元素的Key
    }
}
foreach(var ele in KeyList)
{
    dic.Remove(ele);//再进行删除操作
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325484141&siteId=291194637