如何使用 foreach 修改通用列表中的项目?
我有以下通用列表,其中填充了字符串列表:
List<string> mylist =new List<string>();
myList.add("string1");
myList.add("string2");
假设我想在每个字符串的末尾添加“test”,我怎样才能以简单的方式做到这一点? 直觉上,我尝试了这个,编译正常:
myList.ForEach(s => s = s + "test");
但是如果我然后查看列表的内容,没有任何变化。 我想我可以使用 for 循环来迭代列表,但我正在寻找一些非常简单的东西,并且使用 ForEach 看起来非常整洁......但似乎不起作用。 有任何想法吗?
I have the following Generic List which is populated with a list of string:
List<string> mylist =new List<string>();
myList.add("string1");
myList.add("string2");
Say I want to add 'test' at the end of each string, how can I do it in a simple way? Intuitively, I tried this which compiles ok:
myList.ForEach(s => s = s + "test");
But if I then look at the content of the List, nothing has changed. I guess I could use a for loop to iterate through the List but I'm looking for something very simple and using ForEach looks very neat.... but doesn't seem to work. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是您指定的
Action
在列表的元素上执行,但结果不会放回任何地方......您的s
只是一个局部变量。就地更改列表可能需要实际的
foreach
,但如果您乐意接受新列表作为结果,您可以尝试:不完全相同...但与您一样接近会得到...
The problem is that the
Action
you specified gets executed on the elements of the list, but the result is not put back anywhere... yours
is a local variable only.Changing the list in-place will probably take an actual
foreach
, but if you are happy to take a new list as the result, you could try:Not quite the same... but as close as you'll get...
除非列表类型是可变引用类型,否则不可能这样做(在这种情况下,您仍然无法更改列表中的实际引用,只能更改对象本身)。
原因是
List.ForEach
调用带有签名的Action
委托:这里,参数是按值传递 (这不是
ref
)。 与任何方法一样,按值调用时无法更改输入参数:该代码本质上相当于:
It's not possible to do that unless the list type is a mutable reference type (and in that case, you can't still change the actual reference in the list but the object itself).
The reason is that
List<T>.ForEach
calls aAction<T>
delegate with signature:and here, the argument is passed by value (it's not
ref
). Like any method, you can't change the input argument when it's called by value:The code is essentially equivalent to: