【问题标题】:Dynamically concatenate value in list if pattern matched如果模式匹配,则动态连接列表中的值
【发布时间】:2019-12-08 19:01:38
【问题描述】:

我有一个字符串列表和一个模式数组

List<string> filePaths = Directory.GetFiles(dir, filter).ToList();

string[] prefixes = { "0.", "1.", "2.", "3.", "4.", "5.", "6.", "7.", "8.", "9." };

我想替换 filePaths 中的值,例如:

"1. fileA" becomes "01. fileA"
"2. fileB" becomes "02. fileB"
"10. fileC" becomes "10. fileC" (since "10." is not in prefixes list)

有没有办法在不循环的情况下做到这一点?

【问题讨论】:

    标签: c# list linq replace pattern-matching


    【解决方案1】:

    您可以使用Select

    class Program
    {
        static void Main(string[] args)
        {
            string[] prefixes = { "0.", "1.", "2.", "3.", "4.", "5.", "6.", "7.", "8.", "9." };
            var result = Directory.GetFiles(dir, filter).Select(s => prefixes.Contains(s.Substring(0, 2)) ? "0" + s : s).ToList();
        }
    }
    

    你枚举枚举来检查条件是否需要填充,如果需要填充,否则只返回原始值。

    【讨论】:

      【解决方案2】:

      不需要前缀列表,您可以使用正则表达式向左填充 0:

      string input = "1. fileA";
      string result = Regex.Replace(input, @"^\d+", m => m.Value.PadLeft(2, '0'));
      

      要在整个列表中使用:

      var filePaths = Directory.GetFiles(dir, filter).Select(s => Regex.Replace(s, @"^\d+", m => m.Value.PadLeft(2, '0'))).ToList();
      

      【讨论】:

        猜你喜欢
        • 2016-07-11
        • 2021-10-23
        • 2017-01-11
        • 2011-07-15
        • 2014-10-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多