开发者

Custom Sorting in .NET

开发者 https://www.devze.com 2023-01-09 22:06 出处:网络
I have designed a Class for Parent Child relationship class Category { public strin开发者_JS百科g CatName;

I have designed a Class for Parent Child relationship

  class Category
  {
    public strin开发者_JS百科g 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?


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


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


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


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) );
0

精彩评论

暂无评论...
验证码 换一张
取 消