我有一系列路径(例如C:\Users
,C:\Users\cheese
,D:\Shadow\stuff
,D:\Shadow
)。有没有办法摆脱路径较小的字符串?例如只留下C:\Users\cheese
和D:\Shadow\stuff
并使其快速且内存不密集?
字符串可以按任何顺序排列。
答案 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"
]