修改字典值是possible.What是正确的做法? [英] Modify Dictionary Value is possible.What is the right approach?

查看:113
本文介绍了修改字典值是possible.What是正确的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有填充的字典,我没有控制权。

I have dictionary that is populated and I have no control of.

我需要修改我怎么能做到这一点的价值?

I need to modify the value how can I do that?

我已经把诺迪例如一起解释这个问题。

I have put a noddy example together to explain the problem

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

有什么建议?
非常感谢

Any suggestions? Thanks a lot

推荐答案

我建议你锻炼身体哪个键需要修改的第一个的,然后对这些修改迭代。否则,你将最终修改的集合,而你遍历它,这会抛出异常。因此,例如:

I suggest you work out which keys need modifying first, and then iterate over those modifications. Otherwise you'll end up modifying a collection while you're iterating over it, which will throw an exception. So for example:

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

这篇关于修改字典值是possible.What是正确的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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