简体   繁体   中英

Removing redundant folder paths from a list

I have the following list which contains a series of folder paths. Some of these are redundant so I need to remove them and the final list should only contain the bottom level folders:

Initial list:

var paths = new List<string>
{
    "Pavements/",
    "Pavements/2019_05/",
    "Pavements/2019_06/",
    "Pavements/2019_06/A/",
    "Roads/",
    "Roads/2019_06/"
};

The final List should look like:

paths =
{
    "Pavements/2019_05/",
    "Pavements/2019_06/A/",
    "Roads/2019_06/"
};

ie all the upper level folder paths have been removed.

Does anyone know how I can achieve this? I have a feeling I need a recursive method but am unsure how to go about it. I am using C# but answer in java or something similar is ok. Thanks.

实现此目的的一种方法是使用linq查询,该查询将每个项目与所有其他项目进行比较,并且仅当其他项目都不以它开头时才返回该项目:

paths = paths.Where(path => !paths.Any(p => p != path && p.StartsWith(path))).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM