在字典中循环

2024-01-04

我用这个:

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

  }

问题是我无法更改entry.Value或entry.Key的值

我的问题是,在循环字典时如何更改值或键? 并且,字典允许重复的键吗?如果是的话,我们该如何避免? 谢谢


在循环访问字典中的项目时,无法更改字典条目的值,但如果该值是引用类型的实例,则可以修改该值的属性。

例如,

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说集合被修改了。

为了回答您的具体问题,

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

两者的方法几乎相同。你可以循环遍历字典的副本,正如安东尼·彭格拉姆(Anthony Pengram)所说他的回答 https://stackoverflow.com/questions/6515400/loop-in-dictionary/6515446#6515446,或者您可以循环遍历所有项目以找出需要修改的项目,然后再次循环遍历这些项目的列表:

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);
}

并且,字典允许重复的键吗?如果是的话,我们该如何避免?

字典不允许有重复的键。如果你想要收藏<string, string>配对,看看名称值集合 http://msdn.microsoft.com/en-us/library/system.collections.specialized.namevaluecollection.aspx.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在字典中循环 的相关文章

随机推荐