C# – How to sort a C# list of data where the data is a hierarchical tree (menu)


I'm pulling a dataset into a c# list and to sort it. It's a hierarchical menu:

sample object:

public class NavigationInfo
    public Int32 Id { get; set; }
    public Int32 ParentId { get; set; } 
    public String Text { get; set; }
    public String Url { get; set; }
    public Int32 Sort { get; set; }

The ParentId is recursive to Id and Sort is an ascending integer within the ParentId. How is that done using a collection of NavigationInfo in List<NavigationInfo>?

Best Solution

You can do something like:

var navigationInfos = new List<NavigationInfo>(); //fill this collection

navigationInfos.sort((a,b) => a.Id.CompareTo(b.Id)); //sort by Id
navigationInfos.sort((a,b) => a.ParentId.CompareTo(b.ParentId)); //sort by ParentId

UPDATE: You can also use LINQ and do an OrderBy on the List. This returns a new collection, but is a lot easier to order by multiple criteria, ascending or descending.

var navigationInfos = new List<NavigationInfo>(); //fill this collection
var listSortedById = navigationInfos
                             .OrderBy(n => n.Id).ToList();

var listSortedByParentId = navigationInfos
                               .OrderBy(n => n.ParentId).ToList();

var listSortedByIdThenByParentId = navigationInfos
                              .OrderBy(n => n.Id)
                              .ThenBy(p => p.ParentId)

var orderedByIdDescending = navigationInfos
                                      .OrderByDescending(n => n.Id)