在字典中循环
我用这个:
foreach(KeyValuePair 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 entry in myDict) { entry.Value.SomeNumber = 3; // is okay myDict[entry.Key] = new MyClass(); // is not okay }
尝试在循环其元素时修改字典(或任何集合)将导致InvalidOperationException
表示集合已被修改。
要回答您的具体问题,
我的问题是,如何在循环字典时更改值或键?
两者的方法几乎相同。 你可以像Anthony Pengram在他的回答中所说的那样循环遍历字典的副本,或者你可以循环遍历所有项目以找出你需要修改哪些项目,然后再循环遍历这些项目的列表:
List keysToChange = new List (); foreach(KeyValuePair 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); }
并且,字典是否允许重复密钥? 如果是,我们如何避免?
字典不允许重复键。 如果你想要一个
对的集合,请查看NameValueCollection 。
在循环中更新字典将是一个问题,因为您无法修改字典,因为它被枚举。 但是,您可以通过将字典转换为KeyValuePair<>
对象列表来轻松解决此问题。 您枚举该列表,然后您可以修改字典。
foreach (var pair in dictionary.ToList()) { // to update the value dictionary[pair.Key] = "Some New Value"; // or to change the key => remove it and add something new dictionary.Remove(pair.Key); dictionary.Add("Some New Key", pair.Value); }
对于第二部分,字典中的键必须是唯一的。
KeyValuePair的Key和value是只读的。 但你可以改变这样的值:
dictionary[key].Value = newValue;
但是,如果要更改密钥,则必须删除/添加密钥。
不,字典不允许重复键,它会抛出ArgumentException。
枚举时不能修改键。
我在枚举它时用来改变集合的一种方法是我确实break;
在找到匹配项并修改项目时,退出foreach
循环,并重新启动整个枚举。 这是处理它的一种方式……
不,字典不能有重复的键。 如果您想要按键排序并允许重复的内容,则应使用其他一些数据结构。
你可以这样做
for (int i = 0; i < MyDic.Count; i++) { KeyValuePair s = MyDic.ElementAt(i); MyDic.Remove(s.Key); MyDic.Add(s.Key, "NewValue"); }
而词典不允许重复