0

Apologies if this is a duplicate, but can't find anything that matches everything I need. I have an object, one of the members of which is a Dictionary object, defined as follows:

public class MyTestObject
{
    public int index { get; set; }
    // various other members here
    public Dictionary<string, bool> MyTestValues { get; set; }
}

I have a list of class MyTestObject:

List<MyTestObject> values = new List<MyTestObject>();

I have a loop that runs through each instace of values and a sub-loop which runs through the KVP in the dictionary

foreach (MyTestObject current in values)
{
    foreach (KeyValuePair<string, bool> testCurrent in current.MyTestValues)
    {
    }
}

Within the 2nd loop I need to change boolean value of each of the Dictionary items and this is where I am falling down.

Ideally I'd like to be able to do something similar to the following:

values[current.index].MyTestValues.Where(t => t.Key == testCurrent.Key).Single().Value = true;

i.e., it's using the index member to access the field in the object and update the value. Unfortunately this doesn't work as it says the Value field is read only.

I'm sure I'm getting confused unnecessarily here. Any advice appreciated

Andrew
  • 2,315
  • 3
  • 27
  • 42
  • 1
    It seems like you could just use `values[current.index].MyTestValues[testCurrent.Key] = true` unless I'm misunderstanding something? – Zong Dec 06 '13 at 16:08
  • `I am falling down`. What's the problem? – Hamlet Hakobyan Dec 06 '13 at 16:09
  • @hamlet - the Value field is read only. – Andrew Dec 06 '13 at 16:10
  • @Andrew Don't try and modify the `KeyValuePair`s directly. Access the items in the dictionary through the indexer. – MgSam Dec 06 '13 at 16:13
  • You're trying to modify the contents of the dictionary in a foreach which isn't valid? See this question: http://stackoverflow.com/questions/2260446/how-to-iterate-through-dictionary-and-change-values – Damon Dec 06 '13 at 16:15
  • @Damon. I'm not - in my code you can see I am trying to modify the values object, which is defined outside the foreach loop. I realise you can't modify objects you get from within the for loop which I is why I am doing it this way. – Andrew Dec 06 '13 at 16:17

1 Answers1

3

Just do:

values[current.index].MyTestValues[testCurrent.Key] = true;

It will update the existing value and if the key doesn't exist, it will add the new item in the dictionary with the new key.

Habib
  • 219,104
  • 29
  • 407
  • 436