开发者

how to change the value of dictionary during looping

开发者 https://www.devze.com 2023-01-29 17:31 出处:网络
How do I modify a value in Dictionary?I want to reassign a value to a value in my dictionary while looping on my dictionary like this:

How do I modify a value in Dictionary? I want to reassign a value to a value in my dictionary while looping on my dictionary like this:

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

where dtParams is my Dictionary

I wa开发者_JAVA百科nt to do some thing like this:

string a = "car";    
a = a.Replace("r","t");


The string Replace function returns a new modified string, so you'd have to do something like:

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

EDIT:

Addressed the collection is modified issue (which I didn't think would occur if you access a key that already exists...)


You can't do this directly; you cannot modify a collection while you're enumerating it (also, avoid using ElementAt here; this is a LINQ to Objects extension method and is inefficient for iterating over an entire list). You'll have to make a copy of the keys and iterate over that:

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


when you use replace , it will return a new string instance , you need to assign the value in the dictionary after replace becaue string is immutable in nature


A little lambda will go a long way. ;)

I dropped this into LINQPad and tested it out for you. All the collections have .To[xxx] methods so you can do this quite easily in 1 line.

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();
0

精彩评论

暂无评论...
验证码 换一张
取 消