tags:

views:

566

answers:

3

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

+1  A: 

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)
                              .ToList();

var orderedByIdDescending = navigationInfos
                                      .OrderByDescending(n => n.Id)
                                      .ToList();
Jose Basilio
If you DOWNVOTE, please be mature and courteous enough to leave a comment as to where I am wrong.
Jose Basilio
I agree....that drives me crazy too.....
CSharpAtl
This code works if you have precisely two levels in your hierarchy, otherwise, the code will sort inaccurately.
John Fisher
+1  A: 

If the data comes from DB, you can let the DB send the output in sorted manner (parent first, followed by child Id).

Note: I am assuming DB has the Ids in an order where parent will be a lesser Id than a child.

shahkalpesh
A: 

If your hierarchy will be more than a simple two-level arrangement, you'll need to write a method (probably recursive) that can travel up the tree collecting the entire "path" of each item's ids. Once you have this path, the sorting step is fairly easy.

Add a property to NavigateInfo

public string ItemPath { get; set; }

Then use a method like this to set that property.

public string GetPath(List<NavigationInfo> list, int itemId)
{
    NavigationInfo item = list.SingleOrDefault(x => x.Id == itemId);
    if (item == null)
    {
        return "";
    }
    else
    {
        return GetPath(list, item.ParentId) + "\\" + itemId;
    }
}
John Fisher