按基本路径过滤路径列表的最有效/最优雅的方法是什么?
本文关键字:路径 方法 是什么 有效 过滤 列表 | 更新日期: 2023-09-27 18:02:34
按基本路径过滤所有路径的最有效/最优雅的方法是什么?
我有一个路径列表和一个基本路径,我想让a得到一个路径列表,这些路径是基本路径的子路径:
public IList<string> FilterPathList(IList<string> paths, string basePath)
{
// return a list of paths that are children of the base path
}
样本输入:c:'foo'bar'file1
c:'foo'bar'file2
c:'foo'bar'dir1'file11
c:'foo'bar'dir2'file
c:'foo'other'file1
Base path -> c:'foo'bar
预期输出:c:'foo'bar'file1
c:'foo'bar'file2
c:'foo'bar'dir1'file11
c:'foo'bar'dir2'file
类似于
paths.Where(p => p.StartsWith(basePath)).ToList();
您可能希望充实Where以使比较不区分大小写,当然,除非您对大小写进行规范化。
如果它在列表中,也会返回基本路径。
Using (Parallel)-LINQ:
public IList<string> FilterPathList(IList<string> paths, string basePath)
{
var result = from s in paths.AsParallel()
where s.StartsWith(basePath)
select s;
return result.ToList();
}
AsParallel()
在多个线程中完成工作(如果足够大并且>1个CPU),所以它应该更快,但要注意它可能/将改变列表的顺序。