Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / Languages / C# / May 2008

Tip: Looking for answers? Try searching our database.

Data structure (tree)

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
csharpula csharp - 05 May 2008 17:26 GMT
Hello friends,
I would like to know what is the best way to store a tree structure in
c#? Are there any good implementation examples for seing how to do it?

Thank u!
Peter Duniho - 05 May 2008 18:03 GMT
> I would like to know what is the best way to store a tree structure in
> c#?

That depends on the nature of the tree.  However, it's simple enough to  
write your own class that maintains a tree in whatever manner is  
appropriate for your data.  Common tree implementations would include  
references to children either via a fixed number of instance fields (e.g.  
binary tree) or an instance field that holds a reference to a collection  
of child nodes (e.g. a List<T> instance containing all the children for  
that node).

> Are there any good implementation examples for seing how to do it?

A number of Framework classes use tree-like collections.  You certainly  
could examine them to learn more about different .NET implementations that  
exist.  For example, the Control class (Control.Controls), the TreeView  
class (TreeView.Nodes, and TreeNode.Nodes), and the generic SortedList<T>  
class, to name a few.

Pete
csharpula csharp - 12 May 2008 09:10 GMT
The question is what is the best way to implement a tree structure which
will store the deserialization result of xml structure which represents
a tree. what is the best way? is there any class that already implements
that?

Thank u very much!
Marc Gravell - 12 May 2008 09:19 GMT
Since you are working with xml, would XmlDocument or XDocument suffice?

Marc
csharpula csharp - 12 May 2008 10:03 GMT
But I want to represent a tree in a c# class not via xml ,the result of
xml deserialization will be the data of this class. how to do it? thank
u!
Marc Gravell - 12 May 2008 10:21 GMT
It depends; if you know what the data looks like in advance, then fine -
use XmlSerializer to read the xml into your class structure. But this
won't work for ad-hoc xml.

Example below - is this what you had in mind? If not - please explain
what you do want...

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
[Serializable]
public sealed class TreeNode
{
    [XmlAttribute]
    public string Key { get; set; }
    [XmlAttribute]
    public string Text { get; set; }

    private List<TreeNode> nodes;

    public List<TreeNode> Nodes
    {
        get
        {
            if(nodes == null) nodes = new List<TreeNode>();
            return nodes;
        }
    }

    public override string ToString()
    {
        return Text;
    }
}

static class Program {
    static void Main() {
        TreeNode tree = new TreeNode {
            Key = "A", Text = "Foo",
            Nodes = {
                new TreeNode
                {
                    Key = "B", Text = "Bar",
                    Nodes = {
                        new TreeNode {
                            Key = "C", Text = "Blip"
                        }
                    }
                },
                new TreeNode {
                    Key = "D", Text = "Blop"
                }
            }
        };
        StringBuilder sb = new StringBuilder();
        XmlSerializer xser = new XmlSerializer(typeof(TreeNode));
        using (XmlWriter writer = XmlWriter.Create(sb))
        {
            xser.Serialize(writer, tree);
            writer.Close();
        }

        string xml = sb.ToString();
        Console.WriteLine(xml);

        using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
        {
            TreeNode backAgain = (TreeNode) xser.Deserialize(reader);
        }
    }
}
Marc Gravell - 12 May 2008 10:31 GMT
re-hacked in case you are using C# 2 - actually it is more readable this
way, too...

added 2 .ctor()s for TreeNode:

    public TreeNode() : this("","") { }
    public TreeNode(string key, string text,
        params TreeNode[] nodes)
    {
        Key = key;
        Text = text;
        if (nodes != null && nodes.Length > 0)
        {
            Nodes.AddRange(nodes);
        }
    }

and changed demo setup code:

        TreeNode tree = new TreeNode("A", "Foo",
            new TreeNode("B", "Bar",
                new TreeNode("C", "Blip")
            ),
            new TreeNode("D", "Blop")
        );

Same result, just done differently...

Marc
csharpula csharp - 12 May 2008 12:20 GMT
But my question is if I need to create the TreeNode class by myself and
implement all the tree functionality or I can use some pre defined class
or implment some tree template interface?
Thanks!
Marc Gravell - 12 May 2008 12:36 GMT
> But my question is if I need to create the TreeNode class by myself and
> implement all the tree functionality or I can use some pre defined class
> or implment some tree template interface?
> Thanks!

To come back full-circle, XmlDocument is a fully-functional pre-defined
class for loading an arbitrary tree of data... if you want something in
between, you're going to have to be a lot more specific about what you
want (and probably write it yourself).

In System.Web.UI, there are some interfaces - IHierarchyData,
IHierarchicalEnumerable, IHierarchicalDataSource - but to be honest I
wouldn't worry unless you are using the web tree-view.

Marc

Rate this thread:







Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.