Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alter/modify data from an existing keyValuePair

Tags:

c#

linq

generics

I have this

foreach (KeyValuePair<string, Object> tempData in tempList.ToDictionary(x => x.Key, y => y.Value))
{        
    tempData["fahrzeugA"] = "s";
}

But using tempData["fahrzeugA"] = "s"; will not work.

I get:

Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.KeyValuePair'

What is the correct syntax if I have an existing key fahrzeugA, which I want to alter ?

like image 245
kkkk00999 Avatar asked Apr 23 '26 10:04

kkkk00999


2 Answers

You can apply this :

 var tempList = new List<Test>();
 var dic = tempList.ToDictionary(x => x.Key, y => y.Value);
 foreach (var tempData in dic)
 {
      dic[tempData.Key] = "s";
 }
like image 160
Linh Tuan Avatar answered Apr 25 '26 22:04

Linh Tuan


You can't change the key value pair since it is an immutable struct. The only way to change it is to create a new instance. That instance would live independent from the dictionary.

If you want to change the value in the dictionary, use the indexer property on the dictionary to change the value.

And even then, the dictionary will go out of scope immediately, so there is no use setting it. It won't affect the original list.

like image 31
Patrick Hofman Avatar answered Apr 25 '26 23:04

Patrick Hofman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!