Building Trees from Lists in .NET

- Download source code for .NET 2.0 projects – 3.29 KB
(A single CS file to be included in your .NET 2.0 project) - Download source code for .NET 3.5 projects – 3.29 KB
(A single CS file to be included in your .NET 3.5+ project)
Who Is This Article For?
This article is aimed at .NET developers who need to build a tree (or forest) of objects by loading an array or list of rows from a database, and converting them to a tree structure in memory to use or display.
Introduction
Storing hierarchical data in a database is a very common requirement, whether it be product categories, sports tournaments, or staff hierarchies. Over the years, I have had to create, store in a database and display trees many times, and my method has evolved from having fixed-size hierarchies, to abstract classes providing tree functionality, and finally to the method described in this article. This article describes a very simple way to load data from a table, and convert it into a tree in C# code for .NET 2.0+.
While other articles have been written on the subject, the following goals are not always met:
- You should not need to extend an
abstract
class, because your data class may already extend another class - You shouldn’t need to convert your class to be a partial class
- You shouldn’t need to change your database table: as long as it uses the standard parent ID column referring to its own primary key, it should work
- There shouldn’t need to be any type-casting of parent or child objects
- It should be easy to use
The answer is to define an interface – in this case called ITreeNode<t />
– and then have a utility method to build a tree from that. This article assumes that you have a class defined to hold a single node (e.g. a Category
object), and that when you get a list of nodes from the database each reference to a parent has been instantiated as an object with its ID set, but without a reference to the fully populated parent object, nor its children.
An Example
Let’s look at the very common “Category
” entity, used to categorise products. The database table looks like the following:
Let’s assume that there are just 8 rows in the database, which break the products into two main categories – “Hardware” and “Software” – and then further sub-categories. In this case “Operating Systems” and “Developer Tools” come under “Software”; “Monitors” and “Peripherals” under “Hardware”, and finally “Keyboards” and “Mice” under “Peripherals”, giving the following category hierarchy:
In the database, the rows are as follows:
In order to display this information on a website, you create a “
Category
” class:

public class Category
{
private int _id;
private string _name;
private Category _parent;
private List<Category> _children;
public int Id
{
get { return _id; }
set { _id = value; }
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public Category Parent
{
get { return _parent; }
set { _parent = value; }
}
public List<Category> Children
{
get { return _children; }
set { _children = value; }
}
}
A method is also needed to retrieve all the categories from the database. This will be a “flat” list of each category, i.e. the _parent
field will point to an object which only has its ID populated, and _children
will be null
. A possible example of this method is shown here:
static List<Category> GetListFromDatabase(DbConnection con) {
DbCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT Id, Name, ParentID FROM Category";
cmd.CommandType = CommandType.Text;
DbDataReader reader = cmd.ExecuteReader();
List<Category> categories = new List<Category>();
foreach (DbDataRecord row in reader) {
Category c = new Category();
c.Id = (int)row["Id"];
c.Name = (string)row["Name"];
if (row["ParentID"] != DBNull.Value)
{
c.Parent = new Category();
c.Parent.Id = (int)row["ParentID"];
}
categories.Add(c);
}
reader.Close();
return categories;
}
Once having a list of objects in memory, the ITreeNode
interface comes in handy. The first step is to implement this interface:
public class Category : ITreeNode<Category> {
// contents of class remain as above, because the
// interface is implemented by the Id, Parent, and
// Children properties
}
The interface requires that we have one property referring to the parent of the category (where null
represents a root-level node), and an IList
pointing to the children.
Now we can call the TreeHelper
utility methods to convert the flat array returned from GetListFromDatabase
into a fully populated hierarchy:
IList<Category> topLevelCategories =
TreeHelper.ConvertToForest(GetListFromDatabase());
The variable topLevelCategories
contains two Categories: “Software” and “Hardware”.
Printing Out All Nodes using Nested HTML <ul> and <li> Tags
Using a recursive method, you can easily print out, for example, the full category hierarchy in nested <ul>
tags, as follows:
void Page_Load(object sender, EventArgs e) {
IList<Category> topLevelCategories =
TreeHelper.ConvertToForest(Category.GetListFromDatabase());
Response.Write("<ul>");
foreach(Category topLevelCategory in topLevelCategories) {
RenderCategory(topLevelCategory);
}
Response.Write("</ul>");
}
void RenderCategory(Category category) {
Response.Write("<li>" + category.Name);
if (category.Children.Count > 0) {
Response.Write("<ul>");
foreach(Category child in category.Children) {
RenderCategory(child);
}
Response.Write("</ul>");
}
Response.Write("</li>");
}
This will render the following output:
- Software
- Operating Systems
- Developer Tools
- Hardware
- Monitors
- Peripherals
- Keyboards
- Mice
Searching For a Single Category in the Tree
// in a website, this may use the ASP.NET Cache object.
List<Category> categories = GetCategories();
int categoryId = int.Parse(Request.Params["categoryId"]);
Category currentCategory =
TreeHelper.FindTreeNode(categories, categoryId);
Printing Breadcrumbs
Continuing the example above, this is how the bread crumbs for the current category could be printed:
Category currentCategory = GetCategory();
foreach(Category category in
TreeHelper.Iterators.FromRootToNode(currentCategory))
{
Response.Write(" / " + category.Name);
}
If the current category was “Keyboards”, this would render the following HTML:
/ Hardware / Peripherals / Keyboards
Tree Helper
The TreeHelper
utility class contains numerous other useful methods – such as GetDepth
and HasHierarchyLoop
– and iterators – such as DepthFirstTraversal
, BreadthFirstTraversal
, ClimbToRoot
, FromRootToNode
, and Siblings
.
Check out the fully-documented source code for the full details.
Using Extension Methods and “LINQ to Trees”
If you are using a .NET 3.5 solution, you are able to take advantage of extension methods. This has the effect of implementing methods in interface declarations (which is not possible in older versions of C#), which is probably the most useful aspect of extension methods, and indeed was the reason they were invented.
An example using extension methods:
List<Category> categories = GetCategories().ConvertToForest();
Category current = categories.FindCategory(3);
foreach(Category descendent in current.DepthFirstTraversal()) {
Response.Write("Depth of " + descendent.Name + ": " + descendent.GetDepth();
}
Remember, ConvertToForest
, FindCategory
, DepthFirstTraversal
and GetDepth
are not implemented by the Category
class, it simply “inherits” these methods from the TreeHelper
class, simply by implementing ITreeNode<T>
.
Extension methods go hand-in-hand with LINQ. Yes, strictly speaking, this is simply “LINQ to Objects” rather than “LINQ to trees”, but regardless, it is a new way to query your trees:
List<Category> categoryList = Category.GetCategories();
// Get all categories which are not top level categories,
// and retrieve only the name.
var nonRootCategories =
from c in categoryList.DepthFirstTraversalOfList()
where c.Parent != null
select new { Name = c.Name };
// Get all categories at Depth 2, ordered by name, and
// get the whole category object.
var level2Categories =
from c in categoryList.DepthFirstTraversalOfList()
where c.GetDepth() == 2
orderby c.Name ascending
select c;
he g
tell g
https://tinyurl.com/rsacwgxy g
http://bit.ly/3drY6lE
fujinopromotion.com
separ.es
Rod Oyston
cbd for pain
where to buy viagra in usa
steel screen door
John Deere Service Manuals
description
cbd buds for sale online in usa
cbd buds indica strain of hemp for sale
John Deere Technical Manuals
can you use cbd oil long term for dogs
cbd oil for hemangiosarcoma in dogs
can cbd help dog heart murmur
how long does it take for cbd capsules to kick in
breaking news
hop over to this site
Gita Kinsella
best website hosting
hop over to here
get the facts
best web hosting sites
free sexting
Your Domain Name
webhosting
my latest blog post
Get More Information
cheap flights with jet2 sale flights
you could try this out
안전토토
get more
안전카지노
anonymous
Grady Weathersbee
Grady Hartill
NBA Jerseys
Charlie Bazarte
Nike Air VaporMax Flyknit 3
Yeezy 350
NBA Jerseys
transen in berlin
Adidas yeezy
Jordan 11
Discount UGG Outlet
Adidas yeezy
uc davis cbd oil for dogs
Nike Trainers
Air Max Clearance Sale
Yeezy
Kobe Bryant Jersey 24
Yeezy sliders
best cbd for pain
Adidas Yeezy
Yeezy 350
Timberland Shoes
Air Jordan 1 Mid
Jordan 1
Yeezy 350
Yeezy Cinder
adidas yeezy
jordan shoes
golden goose
Nike Outlet
jordan 11
kd shoes
moncler sale
nike shox for men
jordan shoes
kyrie 6
curry shoes
air jordan
Odilia Mateja
NBA Store
supreme hoodie
kd13
Tyron Cavey
pandora outlet
cheap jordans
Nike Outlet
kd13
off white shoes
adult cam
giannis shoes
goyard
lebron shoes
moncler outlet
jordan shoes
golden goose shoes
golden goose outlet
kyrie irving shoes
UGGS Clearance Sale Outlet
curry 7 shoes
yeezy 500
Yeezy Shoes
supreme hoodie
kd 12
yeezy sneakers
Nike Air VaporMaxm
Yeezy Supply
Nike UK
UGG UK
Nike Outlet
yeezy boost
kyrie 3 shoes
authentic jordans
golden goose
Adidas Yeezy Official Website
Kobe Bryant Jersey
Nike 270
Nike Jordan 1
Air Max 97
retro jordans
jordan shoes
off white clothing
cbd oil in a candle
Cameron Sosh
canada pharmacy online
alberta car towing
roadside assistance
Look At This
find out here now
digital marketing excellence 6th edition
cottage renovation ideas
porno
home remodeling ideas cheap
master plumber look at this site
foundation repair cost dallas tx
마사지알바
Groundbreaking Report on VitalFlow for Prostate
슬롯 게임
San Diego Plumber other
how to report unpaid taxes
안전카지노
Gama Bikes Comfort Bikes for sale
Bike Wheel Mountain Bike Wheels for sale
visit this site right here
Dusty Spitzer
Frederic Schelle
Final mile delivery
안전 놀이터
라이브 베팅
Bettina Nohe
온라인 슬롯
Pretty Gaming
Pest Control Charlotte NC
Christian Heber
Faviola Johal
David Affiliate Marketing
free horror
Eddie Tillema
White Widow Feminized Cannabis Seeds
June YouTube
babydoll lingerie
sex aids for men
ProstaStream website
Shemika Lipsett
출장 안마
Hipolito Dellamora
6 hour adult drivers ed near bethany illinois
Office moving company
Solar Power Florida
JBO.com
aquaplus
Synapse XT reviews
useful reference electrician san diego
Orlando Bawer
wikipedia reference
original site
gaming news
Top cheap flights site
generic cialis for sale
affordable plumbing see this here
Florida Stotelmyer
Best online sale
view - managed it consulting dallas
Andrea Zollner
usine marrakech
fashion accessory
How does Bio Melt Pro work?
Myesha Gangadyal
Hilde Muniz
towing vancouver
Elissa Arocha
plumbers in my area Get More Info
water company dubai
go electricians san diego
pop over here allnewsharings.com
Office furniture removal
baltimore mirror installation
Pumpkin Spice Ry
check here 24 hr electrician
Skinncell Pro: This Review On Skincell Pro Helps Understand Mole and Skin Tags Remover?
visit my profile
splendid spoon soup delivery service
visit homepage breachingnews.com
Going Here backwardsnewsreport.com
Learn More Here b2dnews.com
youtube transcription
who needs their house cleaned
adult chat
TV wall installers
gratis sex treffen
see here now biz market news
take a look at the site here Baria Vungtau News
what is a video marketing strategy?
browse around here phtimesng.com
Office movers
ge parts customer service number
north shore golf club
안동출장마사지
Why Cant I sleep
918kiss
informative post 4News4You.com
Abella Danger
FB88 moi nhat
Fenster Reiniger Roboter
my site BM Sport News
구미출장
discover here Blog1 News
check my source icetimesmagazine.com
pop over to this site americanvalvenews.com
the original source bmsportnews.com
Hosea Calcutt
check 51kannews.com
next page australnews.com
Recommended Reading breaching news
internet 891news.com
discover this phtimesng.com
Learn More Here Arajilinenenews.com
look at these guys adn news 24
click to read 9janewswatch.com
more allnewsnepal.com
home roof repairs
useful reference 7livenews.com
Click Here legalorium.com
how to start your own bank uk
Jenise Zipse
일산명월관
Beginners Feminized Cannabis Seed Mixpack
local cyber insurance news
Discover More 336news.com
read here amarishwardi news 24
Mirror installers
Virginia mirror installation
Jodee Arguillo
baby clothes seperators for closet
site link - vickers lee cunningham
garlic capsules soy free
Check This Out AJD News
Steel Bite Pro Reviews - Does Steel Bite Pro Manage Tooth Decay for Real?
Find Out More Aanewshop.com
Source Tgntimes.com
you can try here ArajiLinenenews.com
official statement AcbLiveNews.com
this 4news4you.com
visit this site right here botapracorrernews.com
see this amelia village news paper
read this post here lindoron
important source Aisa Daily News
try this out Aazadhindnews.com
check this site out bombernews.com
view it Backwardsnewsreport.com
pop over here
Taylor Regelman
Creation entreprise Maroc
address academywebnews.com
see page arvo news
find this Aisa Daily News
Treadmill assembly
browse around this web-site lindoron.com
web link bomber news
this 0751sgnews.com
address boud news
Learn More allgonews.com
find this 4News4You.com
link Suburbanews.com
you can find out more Burkinatimes.com
YOURURL.com Freetowndailynews.com
see post bachstretchnews.com
situs idn poker online
review fasotimes.com
visit the site adnnews24.com
click reference bigest news
look at this web-site radsciencetimes.com
useful source icetimesmagazine.com
canadian and international pharmacy bc
find out here now icetimesmagazine.com
right here BitarkaNews.com
see here now AustralNews.com
click to read more BMSportNews.com
additional reading PhitMesng.com
Mike Rideshare
directory BizmarketNews.com
web link brave news paper
click here now allnewsharings.com
navigate to this website pro-tec-insider.com
Check This Out b2d news
best site atha news
this attock city news
this post baria vungtau news
click bestnewsup.com
porn picture sites
from this source pro-tec-insider.com
Full Article b2dnews.com
pop over here all new sharings
wikipedia reference baria-vungtaunews.com
Get the facts best news up
my link 247RealNews.com
gaming news
custom software development
Карабах это Азербайджан
check my site pro tec insider
company website all new sharings
see here 51kanNews.com
buy generic cialis without prescription canadian pharmacy
watch movies free online
Lemar
clothingline
my site AmarishWardiNews.com
More Help pro-tec-insider.com
dig this AmericanValveNews.com
Website baria-vungtaunews.com
use this link 9JanewsWatch.com
click for more 891News.com
toilet drain plumbing parts
Graduate School
BTC Sprint
우리카지노
best delta credit card
Virginia apartment movers
DC limousine service
DC braiders
fuck ass
explanation achounews.com
her comment is here brawlernews.com
right here legalorium
you could try this out bergamowebnews.com
find out this here achou news
see page scalding coffee
click brawler news
Link W88
try this web-site achou news
game news
ragu z720 video projector hd projectors portable
DC hookah lounge
Apartemen bsd
cinemascope video projectors
Click Here
대구출장후불
managed it services for small businesses plano - cloudskope
4000 lumen video projectors
superslot
VN88
how to get viagra without a doctor
military Stickers Australia
domiciliation casablanca
buy instagram likes
Buy Instagram Followers
environmental benefits of ebooks
what symptoms are doctors looking for to perscribe viagra
K9win.com.co
W88.com
VN88.com
Apple Cider Donut
body building routine for women
heating and air conditioning contractors in my area
buy instagram views
김천출장안마
Free Health Coverage
Mahi Mike
滿¸≥Ó¿Ã≈Õ
rotary encoder distributor
optimal choice cbd oil
메이저사이트
출장안마
fuck google
webvideo
learn this here now
sisteme de copiat
plumber trafalgar
메이저사이트
Los Angeles Copyright Attorney
DC lounges
ceme online
medicare cialis coverage
remove unwanted furniture
北京賽車
virtual terminal
Homepage
안전놀이터
Professional Plumber Gawler
maximum daily dose cialis
cialis 5 mg cuanto dura el efecto
구찌출장안마
see it here 24 hour plumber guildford
FangWallet
link terbaru bola88
navigate here master plumber alexandria
official site Professional Plumber guildford
출장안마
giraffe baby cake
nến nhật
prednisone distributionin body
꽁머니
land for sale in Bahrain
daftar judi online terpercaya
buy tadalafil on line
출장마사지
his comment is here aquarium fish ebooks
Baby List
have a peek at this web-site best aquarium ebooks
does viagra work for normal guys
How does Mellitox work?
용인출장
IDGod
Travel
mixing cialis with viagra
เว็บพนันที่ดีที่สุด
postmates promo code february 2021
social media
Valencia
San Diego Plumber useful site
interaction viagra lipitor
เว็บพนันออนไลน์
คาสิโนออนไลน์
Immigration Lawfirm West Palm Beach
Free Health Insurance
can you take sildenafil and horny goat weed toheyhet
our blogs
rohrreinigungsfirmen
badezimmer sanieren
Immigration Lawyer In My Area
Elmer Feight
성남 출장마사지
click here now emergency plumber Melton
ProstaStream Official website
House Cleaner
lüftungsanlage ratingen
badezimmer düsseldorf
solaranlagen
divi data
best discount car to get sildenafil 20 mg 30 tablets for $8.50
메리트카지노
can you take sildenafil for erectile dysfunction?
check over here
마사지구인구직
visit profile
forex diamond robot
pendik escort kizlar
あなたのDAを強力な被リンク獲得DA70
check my profile
movie projectors home video or whatever
click here to visit
DC office furniture disposal
Maryland pool table movers
Escort Service
Edmund Zamorano
Gay Porn
youtube shadow banning
judi online tanpa modal
sildenafil citrate tablets uses
adwokat
this post
Xvideo
plumbing companies near me from this source
Mirror installation
MARCA DA PAZ
hour driving course near Christoval Texas
BTC Haberleri
Uber Accident Lawyer
ลิงค์ดูบอลสดวันนี้
Rideshare Accident Attorney
제주출장마사지
casino online tanpa deposit
blog
Pingback: mouse
istologio kriptonomirmaton
film izle
Elsie
brain stimulant
Diamond Review.html
ucuz instagram takipci
Best Divorce Attorney Near Me
Emma
best alternatives
สล็อตออนไลน์
제주출장안마
메리트카지노
우리카지노
Steel Bite Pro reviews
สล็อต
제주출장안마
emergency electrician cronulla
Madeline
why not try this out
goede webhosting
how to make money online for beginners
Pinterest
메이저사이트
Fishing Tees
안전토토사이트
Apps Download For Windows 10
Residential Dumpster Rental
Copyright Lawyer
elliptical moving service
sa gaming
dining jobs
best property agents yishun singapore
more about
dog sling for car
대전출장
대전출장마사지
CBD Oil Lube
Apps Download For Windows 10
games for pc download
Fkyedtduarf
Trademark San Antonio Lawyer
천안출장안마
전주출장
CBD Oil Reviews
House painting service
website firma roeselare
opvoeden beagle
Alabama Divorce Attorney
출장
Autoankauf
kitchen accessories click here
נערת ליווי תל אביב
메리트카지노
Elliptical assembly
poker online
forex price action indicator
Divorce Law Firm Near Me
เว็บพนันออนไลน์
Manie Detty
check this out
handmaid's tale megadede
treadmill movers
NBA중계
best supertrend indicator mt4
Nerve shield plus USA
Divorce Lawyer Alabama
digital marketing agency
website url
Gregoria Rosner
Angst Beratung
trading blog
MyHR CVS Login
most profitable forex strategy
used by god clothing
https://www.ubgclothing.com/
royalty free images war
เครดิตฟรี ไม่ต้องแชร์
TV wall installers
Maryland office movers
my blog
출장
clothing websites
Pingback: 34cr4rxq3crq34rq3r4
beleggen in cryptocurrencies
Marica Heckenberg
dmca ignored vps
what video editing software should i use
CBD Oil Lube
Instagram email finder
Panting And Licking Lips
chck this out
Guerin Green
CBD Oil Reviews
judi bola
situs judi slot online terpercaya
human resources phone number
how to make money on reddit
epicondylitis ultrasound
PCB Assembly Manufacturing
creatine optimum nutrition
Alfonzo Choudhury
find this
teapa lucrare-licenta eu creativ trd srl
Best CBD Gummies
สมัคร pg slot โบนัส 100
visit my blog
Paul Buvinghausen
newborn baby checklist
promojagers zeb
Faruqi & Faruqi
Furniture assembly near me
Heating Repair
hacklink
шкаф за пералня
Xxbwkrduarf
Stephaine Boleyn
baby stuff list
movie screens for projectors outdoor
Office furniture installation
View Now
creativ trd srl neata adrian valentin
tv projectors home theater
healt