永发信息网

如何遍历并删除Dictionary集合内容

答案:2  悬赏:0  手机版
解决时间 2021-04-06 08:45
  • 提问者网友:你挡着我发光了
  • 2021-04-06 04:07
如何遍历并删除Dictionary集合内容
最佳答案
  • 五星知识达人网友:思契十里
  • 2021-04-06 04:53
Dictionary ht = new Dictionary

foreach( KeyValuePair crrPair in ht )

{

if ( crrPair.Value.ID == 1 )

ht.remove( crrPair.Key );

}

学会使用 KeyValuePair 是关键。 每个Pair就是Dictionary中的一个元素。
全部回答
  • 1楼网友:荒野風
  • 2021-04-06 05:31
在遍历数据结构的时候,是不可以修改原数据结构的。不然就会抛出错误。   我常用的解决办法是做一份拷贝,遍历这个拷贝。(如果数据不是很大的话)   比如,这个代码:   c#代码   1.idictionary ht = new dictionary();   2.ht.add(1, "one");   3.ht.add(2, "two");   4.   5.// print "one,two"   6.console.writeline(string.join(",", ht.values.select(i => i.tostring()).toarray()));   7.   8.foreach (int key in new list(ht.keys)) {   9. if (key == 1) ht.remove(key);   10.}   11.   12.// print "two"   13.console.writeline(string.join(",", ht.values.select(i => i.tostring()).toarray()));   idictionary ht = new dictionary();   ht.add(1, "one");   ht.add(2, "two");   // print "one,two"   console.writeline(string.join(",", ht.values.select(i => i.tostring()).toarray()));   foreach (int key in new list(ht.keys)) {   if (key == 1) ht.remove(key);   }   // print "two"   console.writeline(string.join(",", ht.values.select(i => i.tostring()).toarray())); 我在遍历的时候,做了一份拷贝。代码是 new list(ht.keys),用到了 list 的构造拷贝函数,   会对 ht.keys 做一份拷贝。之后的 foreach 其实是在对这个拷贝做遍历。 转载 guojian3021886
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯