Recursive Classes

Last post 05-09-2008 4:38 PM by gbogea. 4 replies.

Sort Posts:

  • Recursive Classes

    05-09-2008, 3:57 PM
    • Loading...
    • dan789
    • Joined on 05-31-2006, 9:24 AM
    • NoVa
    • Posts 10

    I have a class that I wrote in C# which has several properties, including a list of the same class that I created. What I'm trying to do is pull out data from a cache and store it as a list of my class. The problem arises in that there is a relationship between the root nodes and child nodes (lets call it "id"). I'm basically trying to mimic a relationship between two datatables using a key, but I can't figure out how to do that with classes. Can anyone help me out? Thanks in advance.

     

    Filed under:
  • Re: Recursive Classes

    05-09-2008, 4:15 PM
    Answer

    You're going to need to setup another field, maybe called ParentID, which would hold the ID value for the container.  You'd use the same concept in a database table to setup a recursive relationship. 

  • Re: Recursive Classes

    05-09-2008, 4:23 PM
    Answer
    • Loading...
    • gbogea
    • Joined on 04-14-2008, 11:17 PM
    • Brazil
    • Posts 204

     Your're trying to build a tree like structure? There's a design pattern to do this called composite. Here's an excellent article about it:

    http://www.dofactory.com/Patterns/PatternComposite.aspx 

    Gabriel Bogéa (http://www.gbogea.com)
    -----------------
    Please 'Mark as Answer' the post(s) that helped you
  • Re: Recursive Classes

    05-09-2008, 4:25 PM

    I generally do something like:

     

    class Foo
    {
        String Name{get;set;}
        Int32 Id{get; set;}
        IEnumerable<Foo> Children {get; set;}
    }

  • Re: Recursive Classes

    05-09-2008, 4:38 PM
    • Loading...
    • gbogea
    • Joined on 04-14-2008, 11:17 PM
    • Brazil
    • Posts 204

    What you're describing is a simplification of the Composite pattern. You'd better take a look at the link on my last post. It will be very useful to you.

     

    Gabriel Bogéa (http://www.gbogea.com)
    -----------------
    Please 'Mark as Answer' the post(s) that helped you
Page 1 of 1 (5 items)