I needed a function that would take a list of folders and removed all sub folders, so that only the top level folders stayed in the list.
For example, given the list:
c:\stuf\morestuff
c:\stuf\morestuff\sub1
c:\otherstuf
c:\otherstuf\sub1
c:\otherstuf\sub2
I wanted the list to be reduced to:
c:\stuf\morestuff
c:\otherstuf
So I came up with this solution:
// remove empty strings and sub folders
private static void CleanUpFolders(List<string> uniqueFolders)
{
uniqueFolders.RemoveAll(
delegate(string curFolder)
{
// remove empty
if (string.IsNullOrEmpty(curFolder))
return true;
// remove sub paths
if (uniqueFolders.Exists(
delegate(string s)
{
if (!string.IsNullOrEmpty(s) &&
curFolder.StartsWith(s) &&
string.Compare(s, curFolder) != 0)
return true;
return false;
} ))
return true;
return false;
}
);
}
This seems to work (not very well tested though) but I was left wondering about some things:
- is there an issue with using variables inside anonymous methods that were declared outside?
- any potential issues with nested anonymous methods?
- any other issues or best practices worth mentioning?