Introduction

The code described here takes Nested Set Model (NSM) data and constructs an object tree from it.

Background

An explanation of Nested Set Models and the relative pros and cons of them are beyond the scope of this article. I suggest Googling for articles by Joe Celko and/or Michael J. Kamfonas. Here are a few articles to get you started though.

Using the Code

In order to construct a hierarchy from a set of NSM data, each data point must contain left and right values. These values are typically integers, but the extension method presented does contain an overload that allows them to be any type that supports IComparable<T>. Here is a sample table storing some simple NSM data:

* For an explanation of the numbering scheme, refer to the articles listed above.

You might query that data like this, for instance:

data = (from d in db.ItemDatas
select d).ToList();

Once you have an IEnumerable<T> of your data, you need a class which supports a hierarchical structure of that class, i.e., a class which has a property responsible for holding "children" of the same type as itself. This class must also support the IPopulate<T> interface. This is necessary so the TreeBuilder can use the data from your list to construct the target "nodes". Simply implement IPopulate<T>.Populate(T payload) to populate the target object with the data from the source. For our example, we might have something like this:

The first lambda points to the property holding the "left" data. The second lambda points to the property holding the "right" data. The third lambda points to the property on the target type where the subordinate hierarchy should be stored.

In the second invocation, the third generic used is int because in our sample, the columns lft and rgt are ints. If you have some alien space data that you would like to use to represent a counting system, specify its type in the third generic parameter. Just remember the generic constraint that it must implement IComparable<T> so that TreeBuilder will know how to order the data.

Points of Interest

I'm sure tons of people will point out more efficient ways to do some of this stuff, and please do post that information, but I am just happy to get this working.

Share

About the Author

Been designing, implementing, and maintianing projects in .Net since the beginning of time...or so it seems. I've done a little of everything before that though; java, vb classic, c, c++, assembly, pascal, basic.