views:

86

answers:

3

I have designed a Class for Parent Child relationship

  class Category
  {
    public string CatName;
    public string CatId;
    public IList<Category> childCategory = new List<Category>();

    public  void addChildCat(Category childCat)
    {
      this.childCategory.Add(childCat);
    }

    public Category SortedCategory(Category cat)
    {
      // Should return the sorted cat i.e topmost parent        
    }
}

Here by Parent will not have Catname or CatId, it will have Child Categories which has CatName, CatId as well as another Child Category List and it goes till "N" categories

  1. Here I need to get the Top Parent with all the child categories sorted by CatName. Any ideas How this can be achieved?
  2. Is my class design GOOD?
+1  A: 

You can use the SortedList to keep track of the child categories instead.

theburningmonk
Won't this prevent my Tree getting expanded?
Sri Kumar
nah, it's fine, you can use it like a normal list, the items are sorted by the key that's all
theburningmonk
A: 

If I understand this, we have a tree structure right? And what is the result you are expecting, the sorted children of the topmost parent (root)?

theraneman
Yes!!! Your correct!!!
Sri Kumar
+1  A: 

You can't because you have not a reference to the parent. You have to add a field:

public Category Parent { get; set; }

and modify the add method to set the parent:

public void addChildCat(Category childCat)
{
  childCat.Parent = this;
  this.childCategory.Add(childCat);
}

You need the parent to get the root:

public static Category SortedCategory(Category cat)
{
  // get the root
  var root = cat;
  while(root.Parent != null) root = root.Parent;

  return root.GetSorted();
}

private Category GetSorted()
{
  var sortedChildren = new List<Category>(childCategories).ConvertAll(c => c.GetSorted());
  sortedChildren.Sort((c1, c2) => c1.CatName.CompareTo(c2.Catname));

  return new Category { CatName = root.CatName, 
                        Catid = root.CatId,
                        childCategories = sortedChildren; }
}
onof
Can pl explain me how sorting is related with public Category Parent { get; set; }?
Sri Kumar
Without the parent you cannot get the root.
onof
Great!!! I got the point! can you pl explain me what happens with GetSorted(). I am new to lambda (i hope so)
Sri Kumar
I got few points, Looks like recursive, yet I am not sure how you perform CatName = root.CatName, Catid = root.CatId, using root!
Sri Kumar
It's creating a new sorted category object copying fields from the root - Object initialization: http://msdn.microsoft.com/en-us/library/bb384062.aspx
onof