【发布时间】:2012-10-22 07:03:21
【问题描述】:
我正在使用 C# 和 .Net 4.0。
我有一个List<string>,其中包含一些值,例如 x1、x2、x3。对于List<string> 中的每个值,我需要连接一个常量值,比如“y”,然后将List<string> 取回为x1y、x2y 和x3y。
有没有 Linq 方法可以做到这一点?
【问题讨论】:
标签: c# linq string-concatenation
我正在使用 C# 和 .Net 4.0。
我有一个List<string>,其中包含一些值,例如 x1、x2、x3。对于List<string> 中的每个值,我需要连接一个常量值,比如“y”,然后将List<string> 取回为x1y、x2y 和x3y。
有没有 Linq 方法可以做到这一点?
【问题讨论】:
标签: c# linq string-concatenation
List<string> yourList = new List<string>() { "X1", "Y1", "X2", "Y2" };
yourList = yourList.Select(r => string.Concat(r, 'y')).ToList();
【讨论】:
list = list.Select(s => s + "y").ToList();
【讨论】:
另一种选择,使用ConvertAll:
List<string> l = new List<string>(new [] {"x1", "x2", "x3"} );
List<string> l2 = l.ConvertAll(x => x + "y");
【讨论】:
ConvertAll 只是因为已经有其他几个基于选择的答案:)
您可以为此使用Select
var list = new List<string>(){ "x1", "x2" };
list = list.Select(s => s + "y").ToList();
【讨论】: