Last active
November 1, 2022 17:17
-
-
Save ip75/baf50b2d235c8301c7ec36e87116f31c to your computer and use it in GitHub Desktop.
C# code to generate tree objects from list of addresses. Item in list looks like "root.child1.child2.child3"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public abstract class BranchNode | |
{ | |
public int Id { get; set; } | |
public string Name { get; set; } | |
public string Path { get; set; } | |
[NotMapped] | |
public string ParentPath | |
{ | |
get | |
{ | |
var lastDotPosition = Path.LastIndexOf('.'); | |
return lastDotPosition == -1 ? null : Path.Substring(0, lastDotPosition ); | |
} | |
set => throw new System.NotImplementedException(); | |
} | |
[NotMapped] | |
public IEnumerable<BranchNode> Children { get; set; } | |
} | |
public static class TreeExtension | |
{ | |
public static T GetParentNode<T>(this IEnumerable<T> collection, | |
T current) where T : BranchNode | |
{ | |
return collection.FirstOrDefault(node => node.Path == current.ParentPath); | |
} | |
public static IEnumerable<T> GenerateTree<T>(this IEnumerable<T> table, T rootNode) where T : BranchNode | |
{ | |
var organizationalNodes = table.ToList(); | |
var rootNodes = organizationalNodes.Where(node => node.ParentPath == rootNode?.Path).ToList(); | |
foreach (var node in rootNodes) | |
{ | |
node.Children = organizationalNodes.GenerateTree(node); | |
} | |
return rootNodes; | |
} | |
} | |
// usage | |
var result = await _context.GetItemsAsync<TerritorialNode>(); | |
result.GenerateTree( null); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment