How to change the value of a dictionary during a loop

How to change the value in the dictionary? I want to reassign a value in my dictionary during a loop in my dictionary as follows:

for (int i = 0; i < dtParams.Count; i++)
{
   dtParams.Values.ElementAt(i).Replace("'", "''");
}

where dtParamsis mineDictionary

I want to do something like this:

string a = "car";    
a = a.Replace("r","t");
+3
source share
4 answers

The Replace string function returns a new modified string, so you will need to do something like:

foreach (var key in dtParams.Keys.ToArray())
{
   dtParams[key] = dtParams[key].Replace("'", "''");
}

EDIT:

The compilation mentioned is a modified problem (which, as I thought, would not occur if you open a key that already exists ...)

+8
source

replace, , . becaue .

+3

; ( ElementAt , LINQ to Objects ). :

foreach(var key in dtParams.Keys.ToList()) // Calling ToList duplicates the list
{
    dtParams[key] = dtParams[key].Replace("'", "''");
}
+3

.;)

LINQPad . . [Xxx] , 1 .

var dtParams = new Dictionary<string, string>();
dtParams.Add("1", "'");
dtParams.Add("a", "a");
dtParams.Add("b", "b");
dtParams.Add("2", "'");
dtParams.Add("c", "c");
dtParams.Add("d", "d");
dtParams.Add("e", "e");
dtParams.Add("3", "'");

var stuff = dtParams.ToDictionary(o => o.Key, o => o.Value.Replace("'", "''"));
stuff.Dump();
+1

Source: https://habr.com/ru/post/1779186/


All Articles