【问题标题】:Concatenate a constant string to each item in a List<string> using LINQ使用 LINQ 将常量字符串连接到 List<string> 中的每个项目
【发布时间】:2012-10-22 07:03:21
【问题描述】:

我正在使用 C# 和 .Net 4.0。

我有一个List&lt;string&gt;,其中包含一些值,例如 x1、x2、x3。对于List&lt;string&gt; 中的每个值,我需要连接一个常量值,比如“y”,然后将List&lt;string&gt; 取回为x1y、x2y 和x3y。

有没有 Linq 方法可以做到这一点?

【问题讨论】:

    标签: c# linq string-concatenation


    【解决方案1】:
    List<string> yourList = new List<string>() { "X1", "Y1", "X2", "Y2" };
    yourList = yourList.Select(r => string.Concat(r, 'y')).ToList();
    

    【讨论】:

    • 感谢您的所有回答。我选择这个作为 Concat 的答案,否则与大多数其他回复类似。 :-)
    【解决方案2】:
    list = list.Select(s => s + "y").ToList();
    

    【讨论】:

      【解决方案3】:

      另一种选择,使用ConvertAll

      List<string> l = new List<string>(new [] {"x1", "x2", "x3"} );
      List<string> l2 = l.ConvertAll(x => x + "y");
      

      【讨论】:

      • 感谢@Paolo,我已经测试过这也可以满足我的需求。我有什么特别的理由应该选择“ConvertAll”而不是“Select”吗?
      • @itsbalur:不是真的,事实上我使用ConvertAll 只是因为已经有其他几个基于选择的答案:)
      【解决方案4】:

      您可以为此使用Select

      var list = new List<string>(){ "x1", "x2" };
      
      list = list.Select(s =>  s + "y").ToList();
      

      【讨论】:

        猜你喜欢
        • 2016-02-23
        • 2010-10-08
        • 1970-01-01
        • 2013-08-28
        • 2019-11-10
        • 1970-01-01
        • 1970-01-01
        • 2019-04-06
        • 2010-09-12
        相关资源
        最近更新 更多