Gopi
Gopi

Reputation: 5877

Custom Sorting in .NET

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?

Upvotes: 1

Views: 180

Answers (4)

JohnP
JohnP

Reputation: 687

Instead of :

public string CatName;
public string CatId;

I would do:

 class Cat
 {
      public string Name { get; set; }
      public string Id { get; set; }
 }

And instead of:

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

I would do:

 var category = new List<Cat>
                               {
                                   new Cat() {Name = "cat1", Id = "123"},
                                   new Cat() {Name = "cat2", Id = "124"},
                                   new Cat() {Name = "cat3", Id = "125"},
                                   new Cat() {Name = "cat4", Id = "126"}
                               };


category.Sort(( cat1, cat2) =>  ((Convert.ToInt32(cat1.Id) > Convert.ToInt32(cat2.Id)) ? 1 : 0) );

Upvotes: 0

onof
onof

Reputation: 17367

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; }
}

Upvotes: 1

theraneman
theraneman

Reputation: 1630

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)?

Upvotes: 0

theburningmonk
theburningmonk

Reputation: 16051

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

Upvotes: 1

Related Questions