Home > Back-end >  c# updating a value inside a List<int> thats inside a dictionary<string, List<int>>
c# updating a value inside a List<int> thats inside a dictionary<string, List<int>>

Time:01-15

Hey all I have a issue with trying to use Lambda with my variable simply because its not a Key, value type of setup. Meaning I don't have the typical Dictionary<string, int>. I have a Dictionary<string, list<int>>)-kind of setup.

public static Dictionary<string, List<int>> sizeOfPhotoBoxes = new Dictionary<string, List<int>>()
    {
        { "box1", new List<int> {357, 272, 8,  5 } },
        { "box2", new List<int> {357, 272, 4,  5 } },
        { "box3", new List<int> {365, 460, 37, 6 } },
        { "box4", new List<int> {365, 265, 8,  6 } },
        { "box5", new List<int> {715, 455, 15, 11 } },
        { "box6", new List<int> {360, 465, 98, 6 } },
        { "box7", new List<int> {360, 465, 44, 6 } },
        { "box8", new List<int> {360, 465, 28, 6 } },
        { "box9", new List<int> {540, 290, 39, 9 } },
        { "box10",new List<int> {540, 290, 10, 9 } }
    };

As you can see I have a Dictionary with a key that's a string and then for its value I have a List that has 4 int values.

I've seen some examples of something similar to mine above but I can not seem to get the value I want from with in the list part.

foreach (var _data in sizeOfPhotoBoxes.Where(w => w.Value.Equals("box2")))
{
    _data.Key[2] = 35; //updating the value in the 3rd place in the list
}

I can get the value since that's the normal key of the dictionary but after that I am at a loss. And the error is:

CS0200 Property or indexer 'string.this[int]' cannot be assigned to -- it is read only

Also tried this that produces the same error as the above one:

var _data = sizeOfPhotoBoxes.Where(w => w.Key == "box2").ToList().ForEach(i => i.Value = 35);

But that too did not work.

I am wanting to update box2's list value that is the 2nd in the list of the 4 without updating all of them.

Any help would be appreciated!

CodePudding user response:

Was able to update via following without loop:

sizeOfPhotoBoxes["box2"][1] = 4;

CodePudding user response:

_data is a tuple of string, List<int>. Ergo, you want to use _data.Value[2] to get access to the List<int> inside of the tuple. The Key represents the "box**" part.

It might be clearer to change the var to the actual type:

...
foreach (KeyValuePair<string, List<int>> _data in sizeOfPhotoBoxes.Where(w => w.Value.Equals("box2")))
...
  •  Tags:  
  • Related