-1

I have an array of strings to delete:

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

Then I have a List of directories:

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

So far I have:

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 );
}

Which gets all directory names that contain a delString. Now I want to replace any delString in every entry of dirs by string.Empty.

How is this accomplished most efficient?

habalulu
  • 15
  • 4

2 Answers2

0

I would do what you're asking like this:

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);
    }
}

That simply tries to replace each of the delStrings in the oldName, one at a time. If the string doesn't exist then you don't change the old string.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
-1

Don't do matches. Instead do two loops:

foreach (var dir in dirs)
{
   foreach (var match in delStrings.ToList())
   {
       if (match == dir)
       {
         dir = string.empty;
         break;
       }
   }
}
GH DevOps
  • 305
  • 1
  • 11