过滤掉以字符串开头的路径字符串

时间:2014-02-18 11:19:04

标签: c#

我有一系列路径(例如C:\UsersC:\Users\cheeseD:\Shadow\stuffD:\Shadow)。有没有办法摆脱路径较小的字符串?例如只留下C:\Users\cheeseD:\Shadow\stuff并使其快速且内存不密集?

字符串可以按任何顺序排列。

1 个答案:

答案 0 :(得分:1)

我会以降序排序路径,然后在枚举路径集合并将其添加到结果时跳过子路径:

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

结果:

[
  "D:\\Shadow\\stuff",
  "C:\\Users\\cheese"
]