Lambda 表达式如何对 List执行 String.Format?
我有一个像这样的列表:
List<String> test = new List<String> {"Luke", "Leia"};
我想使用这样的东西:
test.Select(s => String.Format("Hello {0}", s));
但它不会调整列表中的名称。有没有办法使用 lambda 表达式来改变这些?或者是因为字符串是不可变的所以这不起作用?
I have a list like:
List<String> test = new List<String> {"Luke", "Leia"};
I would like to use something like this:
test.Select(s => String.Format("Hello {0}", s));
but it doesn't adjust the names in the list. Is there a way to use lambda expressions to alter these? Or is it because strings are immutable that this doesn't work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Select 不会修改原始集合;它创建一个新的 IEnumerable您可以使用foreach枚举或转换为列表:
测试仍然包含“Luke”和“Leia” >,并且test2包含“Hello Luke”和“Hello Leia”。
如果要使用 lambda 表达式修改原始列表,可以将 lambda 表达式单独应用于每个列表项,并将结果存储回集合中:
Select doesn't modify the original collection; it creates a new IEnumerable<T> that you can enumerate with a foreach or convert to a list:
test still contains "Luke" and "Leia", and test2 contains "Hello Luke" and "Hello Leia".
If you want to modify the original list with a lambda expression, you can apply the lambda expression to each list item individually and store the result back in the collection:
这里:
不需要花哨。无需滥用 LINQ。只要保持简单即可。
您可以比这更进一步,创建一个扩展方法,如下所示:
用法:
Select
用于投影,实际上旨在在没有副作用的情况下使用。操作列表中的项目显然会产生副作用。事实上,该行除了创建最终可以枚举以生成投影的
IEnumerable
之外,不执行任何操作。Here:
No need to be fancy. No need to abuse LINQ. Just keep it simple.
You could go one step beyond this and create an extension method like so:
Usage:
Select
is for projecting and is really intended to be used in circumstances where there are no side-effects. Manipulating the items in the list very clearly has side-effects. In fact, the linedoesn't do anything except creating an
IEnumerable<string>
that could eventually be enumerated over to produce the projection.另一种可能的解决方案:
One other possible solution:
您可以只执行一个 foreach 语句:
也就是说,如果您只是尝试更新名称。
You could just do a foreach statement:
That is if you are trying to just update the names.