public class DepartmentDigestDto{ [JsonProperty( PropertyName = "id" )] [JsonRequired] public string Id { get; set; } [JsonProperty( PropertyName = "title" )] public string Title { get; set; } [JsonProperty( PropertyName = "parent_department_id" )] public string ParentDepartmentId { get; set; }}
public class DepartmentDigestDto{ [JsonProperty( PropertyName = "id" )] [JsonRequired] public string Id { get; set; } [JsonProperty( PropertyName = "title" )] public string Title { get; set; } [JsonProperty( PropertyName = "parent_department_id" )] public string ParentDepartmentId { get; set; }}
This is one of the returned objects of the List method:
var departments = ( await _departmentClient.List().Unwrap() ).Items;
var departments = ( await _departmentClient.List().Unwrap() ).Items;
I get id from ui and I have to find the way to this id in the departments, i.e. something like this: Office/firstRoom/etc.. (where titles are Title) It seemed to me that it was possible to convert to a tree, so I did the following:
static internal class Extensions{ static public IEnumerable<ExtensionTreeItem<T>> GenerateTree<T, K>( this IEnumerable<T> collection, Func<T, K> idSelector, Func<T, K> parentIdSelector, K rootId = default( K ) ) { foreach ( var item in collection .Where( item => EqualityComparer<K>.Default .Equals( parentIdSelector( item ), rootId ) ) ) { yield return new ExtensionTreeItem<T> { Item = item, Children = collection.GenerateTree( idSelector, parentIdSelector, idSelector( item ) ) }; } }}internal class ExtensionTreeItem<T>{ public T Item { get; set; } public IEnumerable<ExtensionTreeItem<T>> Children { get; set; }}
static internal class Extensions{ static public IEnumerable<ExtensionTreeItem<T>> GenerateTree<T, K>( this IEnumerable<T> collection, Func<T, K> idSelector, Func<T, K> parentIdSelector, K rootId = default( K ) ) { foreach ( var item in collection .Where( item => EqualityComparer<K>.Default .Equals( parentIdSelector( item ), rootId ) ) ) { yield return new ExtensionTreeItem<T> { Item = item, Children = collection.GenerateTree( idSelector, parentIdSelector, idSelector( item ) ) }; } }}internal class ExtensionTreeItem<T>{ public T Item { get; set; } public IEnumerable<ExtensionTreeItem<T>> Children { get; set; }}
And then it's called like this:
var departmentsTree = departments .GenerateTree( department => department.Id, department => department.ParentDepartmentId ) .ToDictionary( x => x.Item.Id, x => x.Children );
var departmentsTree = departments .GenerateTree( department => department.Id, department => department.ParentDepartmentId ) .ToDictionary( x => x.Item.Id, x => x.Children );
It turns out that the key in the dictionary is the very beginning of the path, and the end is somewhere in value. Q: How do I get this way?