2011-07-13 23 views
2

什么是通过基路径过滤所有路径的最有效/优雅的方式?什么是通过基路径过滤路径列表的最高效/优雅的方式?

我有一个路径列表和基本路径,我想获得的是基本路径的孩子路径列表:

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 

回答

4

喜欢的东西:

paths.Where(p => p.StartsWith(basePath)).ToList();

您可能想要充实那些使比较不区分大小写的情况,除非您将事件标准化。

这也将返回基本路径,如果它在列表中。

+0

这不会考虑大小写或\ vs /!考虑:http://stackoverflow.com/questions/3660205/is-there-a-method-to-determine-if-a-file-path-is-nested-within-a-directory-path-i –

+0

@Strilanc我说过它不会考虑到问题,但问题是关于遍历列表的一种优雅方式,可以扩展哪里的内容。此外,问题清楚地说明了它正在扫描的输入类型,不使用正斜杠。 –

+0

对不起,我匆匆地回答了太多的问题,以至于看不到箱子的音符。然而,这个问题没有说明路径保证使用特定的分隔符(这些例子恰好只使用了一个)。即使如此,这是一个危险的假设。 –

3

使用(并行)-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),所以它应该更快,但要注意,它可以/将改变列表的顺序。

+0

除非您使用[AsOrdered()](http://msdn.microsoft.com/zh-cn/library/system.linq.parallelenumerable.asordered.aspx)。 – bzlm