c# – 使用递归从IDictionary中删除项目
发布时间:2020-12-15 19:29:28 所属栏目:百科 来源:网络整理
导读:有人有一个更光滑的方式来做到这一点?看起来它应该比这更容易,但我有心理障碍.基本上我需要从字典中删除项目并递归到也是字典的项目的值. private void RemoveNotPermittedItems(ActionDictionary menu){ var keysToRemove = new Liststring(); foreach (va
有人有一个更光滑的方式来做到这一点?看起来它应该比这更容易,但我有心理障碍.基本上我需要从字典中删除项目并递归到也是字典的项目的值.
private void RemoveNotPermittedItems(ActionDictionary menu) { var keysToRemove = new List<string>(); foreach (var item in menu) { if (!GetIsPermitted(item.Value.Call)) { keysToRemove.Add(item.Key); } else if (item.Value is ActionDictionary) { RemoveNotPermittedItems((ActionDictionary)item.Value); if (((ActionDictionary)item.Value).Count == 0) { keysToRemove.Add(item.Key); } } } foreach (var key in (from item in menu where keysToRemove.Contains(item.Key) select item.Key).ToArray()) { menu.Remove(key); } } 动作词典是这样的: public class ActionDictionary : Dictionary<string,IActionItem>,IActionItem 解决方法
如果你反向迭代字典(从’menu.Count – 1’到零),你真的不需要收集密钥并再次迭代它们.当然,如果你开始删除东西,按顺序迭代将产生变异的集合异常.
我不知道ActionDictionary是什么,所以我无法测试你的确切场景,但这里只是使用Dictionary< string,object>的例子. static int counter = 0; private static void RemoveNotPermittedItems(Dictionary<string,object> menu) { for (int c = menu.Count - 1; c >= 0; c--) { var key = menu.Keys.ElementAt(c); var value = menu[key]; if (value is Dictionary<string,object>) { RemoveNotPermittedItems((Dictionary<string,object>)value); if (((Dictionary<string,object>)value).Count == 0) { menu.Remove(key); } } else if (!GetIsPermitted(value)) { menu.Remove(key); } } } // This just added to actually cause some elements to be removed... private static bool GetIsPermitted(object value) { if (counter++ % 2 == 0) return false; return true; } 我也颠倒了’if’语句,但这只是假设你在调用一个方法来对项目的值进行操作之前你想要进行类型检查……它会以两种方式工作,假设’GetIsPermitted’总是返回TRUE ActionDictionary. 希望这可以帮助. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |