警惕Dictionary和SortedDictionary的顺序陷阱

/*
我们查询资料得知Dictionary的遍历顺序和添加Add时的顺序是一致的,不像 HashTable 顺序不可知;于是我要依赖Dictionary的这种顺序一致特性做一个,固定大小400长度的队列,如果超过400个元素就Remove删除掉老的数 据,保留新的数据;我为什么不用队列Queue因为它没有ContainsKey键查找功能,因为我需要用键来去重.
       当我的程序运行一段时间后发生逻辑问题 ,本来我的程序逻辑是超是400后删除Remove最添加的老数据,但是删除的却是最后添加的新数据,当遍历的时候顺序打乱了,并不是添加的程序,经测试发现字典对象并不能一定保持程序一致,一个使用Remove顺序一致性将得不到保证,经测试
*/




SortedDictionary<string, string> testdict = new SortedDictionary<string, string>(); testdict.Add("a", "a"); testdict.Add("b", "b"); testdict.Add("c", "c"); testdict.Remove("a"); testdict.Add("a", "a"); foreach (KeyValuePair<string, string> kv in testdict) { Response.Write(kv.Key);//输出abc 而不是 bca } Dictionary<string, string> testdict = new Dictionary<string, string>(); testdict.Add("a", "a"); testdict.Add("b", "b"); testdict.Add("c", "c"); testdict.Remove("a"); testdict.Add("a", "a"); foreach (KeyValuePair<string, string> kv in testdict) { Response.Write(kv.Key);//输出abc 而不是 bca }

 

 

 

 

一但使用了Remove字典对象的程序,它已经乱了,现在只有依赖字典加对象双结合才能达到我的要求,悲剧

 

转载于:https://www.cnblogs.com/newlive001/p/3238396.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值