### 如何对数据为分层树（菜单）的C＃数据列表进行排序？

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

ParentId是Id的递归，Sort是ParentId中的升序整数。如何使用`NavigationInfo`中的`List<NavigationInfo>`集合完成？

#### 3 个答案:

``````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：您还可以使用LINQ并在列表上执行OrderBy。这会返回一个新的集合，但通过多个标准（升序或降序）更容易订购。

``````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();
``````

``````public string ItemPath { get; set; }
``````

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