I have a list of locations as strings;
locA/locB
locA/locB/locH
locC/locD/locE
locC/locD/locE/locK
locF/locG
I've been trying to create an object that uses the same structure as the list of locations passed to it;
eg Something like..
var myHObject=CreateHeirarchicalObjectFromList(myStringListOfLocations);
I'm having problems looping through the list without almost doing it manually with loads of loops. Is there an easier way, maybe recursion?
I want to end up with an object like this;
.locA
.locB
.locH
.locC
.locD
.locE
.locK
.locF
.locG
That I can use to create a visual hierarchy.
Prob not the best but knocked up in LinqPad, will reformat in a sec..
void Main()
{
var strings = new string[]{"locA/locB","locA/locB/locH",
"locC/locD/locE","locC/locD/locE/locK","locF/locG"};
var folders = Folder.Parse(strings);
folders.Dump();
}
public class Folder
{
public string Name { get; set; }
public List<Folder> Folders { get; internal set; }
public Folder()
{
Folders = new List<Folder>();
}
//Presume that each string will be folder1/folder2/folder3
public static IEnumerable<Folder> Parse(IEnumerable<string> locations)
{
var folders = new List<Folder>();
foreach (string location in locations)
{
string[] parts = location.Split('/');
Folder current = null;
foreach (string part in parts)
{
var useFolders = current != null ?
current.Folders : folders;
current = useFolders.SingleOrDefault(f => f.Name == part) ?? new Folder() { Name = part };
if (!useFolders.Contains(current)) { useFolders.Add(current); }
}
}
return folders;
}
}
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.