Note that there are some explanatory texts on larger screens.

plurals
  1. POQuery or algorithm to generate a structure to populate a tree (C#, LINQ)
    primarykey
    data
    text
    <p>I couldn't find or come up with a generic and elegant algorithm that would let me populate the tree-like structure. The simplest example is a blog archive: I have a bunch of records which can be selected and sorted by date. I want to have a tree where years may be top level, months are next level and actual post titles are next again.</p> <p>So far I've came up with a naive straight forward implementation that works, but I'm sure that could be improved using LINQ, etc. Here I just sort records by date and iterate checking if the year or month has changed, and add tree nodes accordingly. "BlogEntry" is a class that has a reference to both a parent and children and is later used to generate HTML.</p> <p>I welcome suggestions on improving the algorithm!</p> <pre><code>IEnumerable&lt;Post&gt; posts = db.Posts.OrderBy(p =&gt; p.DateCreated); var topPost = posts.First(); int curYear = topPost.DateCreated.Year; int curMonth = topPost.DateCreated.Month; //create first "year-level" item var topYear = new BlogEntry { Name = topPost.DateCreated.Year.ToString().ToLink(string.Empty) }; entries.Add(topYear); var currentYear = topYear; var topMonth = new BlogEntry { Name = topPost.DateCreated.ToString("MMMM").ToLink(string.Empty), Parent = currentYear }; currentYear.Children.Add(topMonth); var currentMonth = topMonth; foreach (var post in posts) { if(post.DateCreated.Year == curYear) { if (post.DateCreated.Month != curMonth) { //create "month-level" item var month = new BlogEntry { Name = post.DateCreated.ToString("MMMM").ToLink(string.Empty), Parent = currentYear }; currentYear.Children.Add(month); currentMonth = month; curMonth = post.DateCreated.Month; } //create "blog entry level" item var blogEntry = new BlogEntry { Name = post.Title.ToLink("/Post/" + post.PostID + "/" + post.Title.ToSeoUrl() ), Parent = currentMonth }; currentMonth.Children.Add(blogEntry); } else { //create "year-level" item var year = new BlogEntry { Name = post.DateCreated.Year.ToString().ToLink(string.Empty) }; entries.Add(year); currentYear = year; curMonth = post.DateCreated.Month; curYear = post.DateCreated.Year; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload