using System.Collections.Generic;
public static void Main()
var list = new List<PermissionsResultDto>();
list.Add(new PermissionsResultDto()
Id = 1, IsGranted = false, Name = "Child1"
list.Add(new PermissionsResultDto()
Id = 2, IsGranted = false, Name = "Child1.Child2"
list.Add(new PermissionsResultDto()
Id = 3, IsGranted = false, Name = "Child1.Child3"
list.Add(new PermissionsResultDto()
Id = 4, IsGranted = false, Name = "ChildT0.Child1"
list.Add(new PermissionsResultDto()
Id = 5, IsGranted = false, Name = "Child10"
list.Add(new PermissionsResultDto()
Id = 6, IsGranted = false, Name = "Child10.Child11"
list.Add(new PermissionsResultDto()
Id = 7, IsGranted = false, Name = "Child0.Child11"
list.Add(new PermissionsResultDto()
Id = 8, IsGranted = false, Name = "Child1.Child2.Child4"
var matrix = CreateMatrixForPermission(list);
var result = new List<PermissionsTreeViewDto>();
MatrixToTreePermission(result, matrix, 0);
Console.WriteLine(result.Count());
public static List<List<PermissionsResultDto>> CreateMatrixForPermission(List<PermissionsResultDto> permissionCollection)
var matrix = new List<List<PermissionsResultDto>>();
foreach (var item in permissionCollection)
matrix.Add(item.Name.Split('.').Select(x => new PermissionsResultDto()
Id = item.Id, Name = x, }
public static void MatrixToTreePermission(List<PermissionsTreeViewDto> result, List<List<PermissionsResultDto>> matrix, int level)
group node by node[level] into grouping
foreach (var node in nodes)
var item = new PermissionsTreeViewDto()
Id = groupKey.Id, Label = groupKey.Name, Selected = groupKey.IsGranted
MatrixToTreePermission(result, node.ToList(), level + 1);
var child = new PermissionsTreeViewDto()
Id = node.Key.Id, Label = node.Key.Name, Selected = node.Key.IsGranted
if (item.Children == null)
item.Children = new List<PermissionsTreeViewDto>();
item.Children.Add(child);
public class PermissionsResultDto : IEquatable<PermissionsResultDto>
public bool Equals(PermissionsResultDto other)
if (Object.ReferenceEquals(other, null))
if (Object.ReferenceEquals(this, other))
return Id.Equals(other.Id) && Name.Equals(other.Name);
public override int GetHashCode()
int hashTextual = Name == null ? 0 : Name.GetHashCode();
int hashDigital = Id.GetHashCode();
return hashDigital ^ hashTextual;
public class PermissionsTreeViewDto
public List<PermissionsTreeViewDto> Children