【问题标题】:How to delete substrings given in an array from entries in a list in c# [duplicate]如何从c#列表中的条目中删除数组中给定的子字符串[重复]
【发布时间】:2022-02-16 04:14:07
【问题描述】:

我有一个字符串数组要删除:

string[] delStrings = {"aaa", "bbb", "ccc", "ddd"}

然后我有一个目录列表:

List<string> dirs = new(Directory.EnumerateDirectories(path));

到目前为止我有:

var matches = from dir in dirs
              where delStrings.Any( str => dir.Contains(str) )
              select dir;

foreach ( string oldName in matches ) {
  // ==> how to delete any delString <==
  // something such
  // string subString = delStrings.Any( str => oldName.Contains(str) )

  string newName = oldName.Replace( subString, string.Empty );
  System.IO.Directory.Move( oldName, newName );
}

获取所有包含 delString 的目录名称。 现在我想将 dirs 的每个条目中的任何 delString 替换为 字符串。空。

如何做到最有效?

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    我会按照你的要求做:

    foreach (string oldName in Directory.EnumerateDirectories(path).ToList())
    {
        string newName = delStrings.Aggregate(oldName, (a, x) => a.Replace(x, String.Empty));
        if (newName != oldName)
        {
            System.IO.Directory.Move(oldName, newName);
        }
    }
    

    这只是尝试替换oldName 中的每个delStrings,一次一个。如果字符串不存在,则不要更改旧字符串。

    【讨论】:

    • 非常感谢。这为我完成了这项工作。
    【解决方案2】:

    不要进行比赛。而是做两个循环:

    foreach (var dir in dirs)
    {
       foreach (var match in delStrings.ToList())
       {
           if (match == dir)
           {
             dir = string.empty;
             break;
           }
       }
    }
    

    【讨论】:

    • 这不符合 OP 的要求。
    猜你喜欢
    • 2023-03-15
    • 2017-09-10
    • 2018-06-09
    • 2020-05-01
    • 1970-01-01
    • 2011-03-23
    • 1970-01-01
    • 2016-04-26
    • 2011-12-08
    相关资源
    最近更新 更多