如何在循环过程中更改字典的值
如何修改字典中的值?我想在循环字典时将值重新分配给字典中的值,如下所示:
for (int i = 0; i < dtParams.Count; i++)
{
dtParams.Values.ElementAt(i).Replace("'", "''");
}
其中 dtParams 是我的字典
我想做这样的事情:
string a = "car";
a = a.Replace("r","t");
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 want to do some thing like this:
string a = "car";
a = a.Replace("r","t");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
字符串替换函数返回一个新的修改后的字符串,因此您必须执行以下操作:
编辑:
解决了集合被修改的问题(我认为如果您访问已经存在的密钥,则不会发生这种情况......)
The string Replace function returns a new modified string, so you'd have to do something like:
EDIT:
Addressed the collection is modified issue (which I didn't think would occur if you access a key that already exists...)
你不能直接这样做;枚举集合时无法对其进行修改(另外,请避免在此处使用
ElementAt
;这是 LINQ to Objects 扩展方法,对于迭代整个列表而言效率较低)。您必须复制密钥并对其进行迭代: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:当你使用replace时,它会返回一个新的字符串实例,你需要在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
一点 lambda 会有很长的路要走。 ;)
我将其放入 LINQPad 中并为您进行了测试。所有集合都有 .To[xxx] 方法,因此您可以在 1 行中轻松完成此操作。
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.