Hierarchical c# sorting recursively

parent child hierarchy c#
c# recursive hierarchy
c# hierarchical list
build hierarchy from flat list c#
datatable recursive c#
populate treeview from database c# recursion
linq recursive parent child
data hierarchy in c#

I have a data structure typed like this:

 class Something {
   public string Name { get; set; }
   public List<Something> Children {get; set;}

   public Something() {
     Children = new List<Something>();
   }
 }

Example Data:

    var one = new Something();
    one.Name = "B";

    var two = new Something();
    two.Name = "A";

    var three = new Something();
    three.Name = "C";

    one.Children.Add(new Something { Name = "F"});
    one.Children.Add(new Something { Name = "E"});
    one.Children.Add(new Something { Name = "D"});

    three.Children.Add(new Something { Name = "F"});
    three.Children.Add(new Something { Name = "E"});
    three.Children.Add(new Something { Name = "D"});

    var data = new List<Something>();
    data.Add(one);
    data.Add(two);
    data.Add(three);

I need a function to sort the field at all levels. The depth of the tree is arbitrary.

I have this so far:

public static List<Something> SortTree(List<Something> node) {
  if (node == null) {
    return null;
  }

  return node
    .OrderBy(x => x.Name)
    .Select(y => {
       if (y.Children.Count() > 0) {
         var t = y.Children;
         SortTree(t.ToList());
       }

       return y;
    })
    .ToList();
  }

Calling SortTree(data) returns the data with only the parent level sorted.

Thanks for the help.

In your line

SortTree(t.ToList());

you are directly discarding the result since you're never actually updating the Children field.

You probably want something like

y.Children = SortTree(y.Children.ToList());

Although I would try to change your SortTree() to a method that does not return a value.

Sorting Parent-Children's data as an hierarchical tree, We are using recursive CTE only for one-time-job to build the content of the column, which we will use for the sorting My basic idea for  Recursive Selection Sort; Median of sliding window in an array; Minimum number of swaps required to sort an array of first N number; Maximum number of unique values in the array after performing given operations; Efficiently merging two sorted arrays with O(1) extra space and O(NlogN + MlogM) Number of pairs in an array with the sum greater than 0

In case you have a mesh (not just a tree) with loops (child is parent of itself) you'll be in trouble with recoursion. Another possible issue (the same stack overflow) is when the graph is too deep ("The depth of the tree is arbitrary"). I suggest a bit modified BFS algorithm

public static List<Something> SortTree(List<Something> node) {
  Queue<List<Something>> agenda = new Queue<List<Something>>();

  agenda.Enqueue(node);

  HashSet<List<Something>> alreadySorted = new HashSet<List<Something>>() { null };

  while (agenda.Any()) {
    var current = agenda.Dequeue();

    if (alreadySorted.Add(current)) {
      current.Sort((left, right) => string.Compare(left.Name, right.Name));

      foreach (var child in current)
        agenda.Enqueue(child.Children);
    }
  }

  return node;
}

Recursive method turning flat structure to recursive, Recursive method turning flat structure to recursive · c# linq recursion. I often end up working with systems where the data is delivered with some Id property and  For a hierarchical collection, wouldn't it be cool if we were able to write something similar to query for objects anywhere in the hierarchy: myItems.Traverse(i = > i.Id == 25 ) This can be achieved by writing an extension method which internally uses the Y Combinator to recursively traverse the hierarchy.

If you want to do recursive anything, you do not get around writing your own loop. At least to my knowledge (wich is far from complete), you can not continue to just use linq. You have to write the sorting loop yourself.

At wich point recursively calling "SortTree(current);" becomes trivial

Learning C# Programming with Unity 3D, This statement does not call on the Recurse() function again, so the recursion stops here. The reason This way we'll have something to sort through. The above code will produce a pretty interesting hierarchy of game objects in the scene. Create a Recursive Hierarchy Group (Report Builder and SSRS) 03/01/2017; 2 minutes to read +1; In this article. In Reporting Services paginated reports, a recursive hierarchy group organizes data from a single report dataset that includes multiple hierarchical levels, such as the report-to structure for manager-employee relationships in an organizational hierarchy.

Retrieving Hierarchically Recursive Data Iteratively, Organizational structures (employees) are recursive hierarchies. Recursively hierarchical data can be retrieved and processed recursively. For  Recursive Bubble Sort; Maximum sum path in a Matrix; Count of subarrays of an Array having all unique digits; Count of subsets with sum equal to X using Recursion; Longest alternating subsequence in terms of positive and negative integers; Check if an array is sorted and rotated using Binary Search; How to flatten a Vector of Vectors or 2D Vector in C++

Mastering ASP.NET with Visual C#, override settings at higher levels, exactly as the documentation (sort of) states. test2.aspx.csfile transfers execution back—and you stillget the recursion error. Site Hierarchy versus Directory Hierarchy Go back and look at 499 THE WEB. Recursively hierarchical data can be retrieved and processed recursively. For each parent item, such as a directory or a window, the function processing the structure can call itself for each child. It is very easy to design a way to retrieve hierarchical data recursively.

Depth-First Hierarchy in C# - Vin Jenks, Now imagine looping through these records and building a new string for each, which would contain the hierarchy, from the bottom-up. Recursion  Recursive Insertion Sort; Maximum sum path in a Matrix; Count of subarrays of an Array having all unique digits; Count of subsets with sum equal to X using Recursion; Longest alternating subsequence in terms of positive and negative integers; Check if an array is sorted and rotated using Binary Search; How to flatten a Vector of Vectors or 2D Vector in C++

Comments
  • As a note the .ToList() in SortTree(t.ToList()); doesn't seem to be needed since y.Children is already a List.
  • I've accepted this as an answer as it was the missing part I was looking for. However I would recommend looking at Dmitry's answer if you don't want to run into any issues that he outlines in his comment.
  • Thanks Dmitry this works as well. Do you have any good documentation you recommend on Queues and Stacks?
  • @codeAline: I think standard MSDN manual is the best to start from: docs.microsoft.com/en-us/dotnet/api/… docs.microsoft.com/en-us/dotnet/api/…
  • Do you mean using foreach instead of select? Do you mind posting an example please.