Andrew
Andrew

Reputation: 2335

Setting dictionary value from withn foreach loop

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

Upvotes: 0

Views: 156

Answers (1)

Habib
Habib

Reputation: 223247

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.

Upvotes: 3

Related Questions