-1

I have a collection of paths (e.g. C:\Users, C:\Users\cheese, D:\Shadow\stuff ,D:\Shadow). Is there any way to get rid of strings that are lesser path? e.g. to only leave C:\Users\cheese and D:\Shadow\stuff and make it FAST and memory un-intensive?

It is important that the strings can come in any order.

Ondrej Janacek
  • 12,486
  • 14
  • 59
  • 93
zaitsman
  • 8,984
  • 6
  • 47
  • 79
  • 1
    Please share what you have tried. Is your solution too slow? Eating too much memory? How many strings do you intend to support? I like the motto: Make it work, make it right, make it fast. – Ed Chapel Feb 18 '14 at 11:21
  • 1
    It is possible, if you can define `lesser path`. – oleksii Feb 18 '14 at 11:21
  • Why not count the back-slashes? – Emond Feb 18 '14 at 11:26
  • @Erno because `C:\Foo\Bar\Baz` _probably_ shouldn't replace `C:\Bar`, but I'd love to see OP answer @oleksii. Also with @Ed, removing a few string probably isn't going to make your application any noticeable faster or less memory-intensive. – CodeCaster Feb 18 '14 at 11:27
  • @CodeCaster Ah, yes that makes sense. So remove all parent paths for the collection. – Emond Feb 18 '14 at 11:28
  • @oleksii the wording was pretty bad on my part, it should've been path closest to the root. (e.g. C:\Users is less in length than C:\Users\cheese). – zaitsman Feb 18 '14 at 12:10

1 Answers1

1

I would order paths in descending way, and then just skip sub-paths when enumerating collection of paths and adding them to results:

string[] paths = { @"C:\Users", @"C:\Users\cheese", @"D:\Shadow\stuff", @"D:\Shadow" };

string currentPath = "";
List<string> result = new List<string>();
var comparer = StringComparer.InvariantCultureIgnoreCase;

foreach (var path in paths.OrderByDescending(p => p, comparer))
{
    if (currentPath.IndexOf(path, StringComparison.InvariantCultureIgnoreCase) >= 0)
        continue;

    result.Add(path);
    currentPath = path;
}

Result:

[
  "D:\\Shadow\\stuff",
  "C:\\Users\\cheese"
]
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459