我有填充的字典,我无法控制.
我需要修改值我该怎么做?
我把一个简单的例子放在一起来解释这个问题
class Program
{
static void Main(string[] args)
{
Dictionary<Customer, int> CustomerOrderDictionary = new Dictionary<Customer, int>();
CustomerOrderDictionary.Add(new Customer { Id = 1, FullName = "Jo Bloogs" },3);
CustomerOrderDictionary.Add(new Customer { Id = 2, FullName = "Rob Smith" },5);
//now I decide to increase the quantity but cannot do the below as value has no setter
foreach (var pair in CustomerOrderDictionary)
{
if(pair.Key.Id==1)
{
pair.Value = 4;///ERROR HERE
}
}
}
}
public class Customer
{
public int Id { get; set; }
public string FullName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
有什么建议?非常感谢
我建议你工作了哪个键需要修改第一,然后遍历这些修改.否则,当你迭代它时,你最终会修改一个集合,这将引发异常.例如:
// The ToList() call here is important, so that we evaluate all of the query
// *before* we start modifying the dictionary
var keysToModify = CustomerOrderDictionary.Keys
.Where(k => k.Id == 1)
.ToList();
foreach (var key in keysToModify)
{
CustomerOrderDictionary[key] = 4;
}
Run Code Online (Sandbox Code Playgroud)
这里的问题是对的类型KeyValuePair是一个只读对象,不能修改.此外,该KeyValuePair集合是一种查看字典内容的方式(不更改它).
你想在这里做的只是直接修改字典.该Key在KeyValuePair可用于更新词典中的同一个条目.
if(pair.Key.Id==1) {
CustomerOrderDictionary[pair.Key] = 4;
}
Run Code Online (Sandbox Code Playgroud)
编辑
正如Jon指出的那样,赋值将使迭代器无效.最简单但无效的路线是在循环开始时复制枚举器.
foreach (var pair in CustomerOrderDictionary.ToList())
Run Code Online (Sandbox Code Playgroud)