Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify Dictionary Value is possible.What is the right approach?

Tags:

c#

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

like image 213
user9969 Avatar asked Oct 19 '10 18:10

user9969


2 Answers

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;
}
like image 188
Jon Skeet Avatar answered Nov 15 '22 04:11

Jon Skeet


The problem here is that pair is typed to KeyValuePair which is a readonly object and can't be modified. Additionally the KeyValuePair collection is a way of viewing the contents of the dictionary (not changing it).

What you want to do here is just modify the dictionary directly. The Key in the KeyValuePair can be used to update the same entry in the dictionary.

if(pair.Key.Id==1) {
  CustomerOrderDictionary[pair.Key] = 4;
}

EDIT

As Jon pointed out the assignment will invalidate the iterator. The simplest, but ineffecient route, is to copy the enumerator at the start of the loop.

foreach (var pair in CustomerOrderDictionary.ToList())
like image 22
JaredPar Avatar answered Nov 15 '22 05:11

JaredPar