回路词典 [英] Loop in Dictionary

查看:144
本文介绍了回路词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用这个:

foreach(KeyValuePair<String,String> entry in MyDic)
  {
      // do something with entry.Value or entry.Key

  }

问题是我不能更改entry.Value或entry.Key的值

The problem is that I can't change the value of entry.Value or entry.Key

我的问题是如何在循环时更改值或键通过字典?
和,字典允许重复键?如果是,我们如何避免?
谢谢

My question is that how can i change the value or key when looping through a dictionary? And, does dictionary allow duplicated key? And if yes, how can we avoid ? Thank you

推荐答案

虽然循环遍历字典中的项目,但不能更改字典条目的值,

You cannot change the value of a dictionary entry while looping through the items in the dictionary, although you can modify a property on the value if it's an instance of a reference type.

例如,

public class MyClass 
{
    public int SomeNumber { get; set;}
}

foreach(KeyValuePair<string, MyClass> entry in myDict)
{
    entry.Value.SomeNumber = 3; // is okay
    myDict[entry.Key] = new MyClass(); // is not okay
}

尝试修改字典循环其元素将导致 InvalidOperationException 表示集合已修改。

Trying to modify a dictionary (or any collection) while looping through its elements will result in an InvalidOperationException saying the collection was modified.

要回答您的具体问题, / p>

To answer your specific questions,


我的问题是,如何在循环遍历字典时更改值或键?

My question is that how can i change the value or key when looping through a dictionary?

两者的方法将大致相同。您可以在Anthony Pengram在他的答案中说,或者您可以循环浏览所有项目以找出需要修改的项目,然后通过这些项目的列表再次循环:

The approach to both will be pretty much the same. You can either loop over a copy of the dictionary as Anthony Pengram said in his answer, or you can loop once through all the items to figure out which ones you need to modify and then loop again through a list of those items:

List<string> keysToChange = new List<string>();
foreach(KeyValuePair<string, string> entry in myDict)
{
    if(...) // some check to see if it's an item you want to act on
    {
        keysToChange.Add(entry.Key);
    }
}

foreach(string key in keysToChange)
{
   myDict[key] = "new value";

   // or "rename" a key
   myDict["new key"] = myDict[key];
   myDict.Remove(key);
}




字典是否允许重复键?如果是,我们如何避免?

And, does dictionary allow duplicated key? And if yes, how can we avoid ?

字典不允许重复键。如果你想要一个< string,string> 的集合,请查看 NameValueCollection

A dictionary does not allow duplicate keys. If you want a collection of <string, string> pairs that does, check out NameValueCollection.

这篇关于回路词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆