user2818430
user2818430

Reputation: 6029

C# List<Item> parent child relation, order items alphabetically

I have a class:

public class Item
{
   public Item()
   {
      Items = new List<Item>();
   }

   public string ItemId { get; set; }
   public string ParentId { get; set; }
   public string Title { get; set; }
   public List<Item> Items { get; set; }

}

Now I can create a list:

List<Item> list = new List<Item>();

How can I recursively order the list and it's children alphabetically?

This is my attempt:

  list.OrderList();


  private static void OrderList(this List<Item> list)
    {
        foreach (Item item in list)
        {
            if (item != null && item.Items != null && item.Items.Count > 0)
            {
                item.Items.OrderChildList();
            }
        }
    }

    private static void OrderChildList(this List<Item> list)
    {
        list = list.OrderBy(t => t.Title).ToList();            
    }

Upvotes: 1

Views: 890

Answers (4)

Kevin
Kevin

Reputation: 2291

In place sort:

static void OrderList(List<Item> l)
{
    l.Sort((i1,i2) => i1.Title.CompareTo(i2.Title));
    foreach (var item in l)
        OrderList (item.Items);
}

Upvotes: 1

CrookedBadge
CrookedBadge

Reputation: 116

This worked for me:

public void OrderList()
{
    if (Items.Count == 0)
        return;
    Items = Items.OrderBy(e => e.Title).ToList();
    Items.ForEach(e => e.OrderList());
}

Upvotes: 0

Rob
Rob

Reputation: 27357

This should do it..?

private static void OrderList(Item item)
{
    foreach (Item item in item.Items)
    {
        if (item != null && item.Items != null && item.Items.Count > 0)
        {
            OrderList(item);
        }
    }
    Items = Items.OrderBy(i => i.Title).ToList()
}

Upvotes: 1

Richard
Richard

Reputation: 108995

As noted in the questions, each list is sorted independently. Thus a simple recursion will do:

void SortRecursively(List<Item> items) {
  foreach (var item in items) {
    item.Items = item.Items.OrderBy(i => i.Title).ToList();
    SortRecursively(item.Items);
  }
}

(This assumes that this is an acyclic graph, handling cycles would require tracking which items have been sorted and skipping them.)

Upvotes: 1

Related Questions