我有以下课程
public class Node
{
public string Name { get; set; }
public string Image { get; set; }
public string Symbol { get; set; }
public string KaartNum { get; set; }
public List<Node> children { get; set; }
}
这是一个树形列表,将节点保存在该节点内,我想按KaartNum
排序,然后按Name
排序,我尝试了以下方法进行排序以获得所需的结果。
List<Node> SortedList = obNodeList
.OrderBy(o => Convert.ToInt16(o.Kaart))
.ThenBy(o => o.Name))
.ThenBy(c=>c.children.OrderBy(p=>p.N))
.ToList();
它仅在根类级别有效,而不适用于嵌套子级
属性,我只需要对Name
属性进行排序。
答案 0 :(得分:1)
求助:
List<Node> SortParents(List<Node> source) {
if(source == null || source.Count == 0) return source;
return
source
.OrderBy(o => Convert.ToInt16(o.KaartNum))
.ThenBy(o => o.Name)
.Select(o => new Node() {
Name = o.Name,
Image = o.Image,
Symbol = o.Symbol,
KaartNum = o.KaartNum,
children = SortChildren(o.children)
})
.ToList();
}
List<Node> SortChildren(List<Node> source) {
if(source == null || source.Count == 0) return source;
return
source
.OrderBy(o => o.Name)
.Select(o => new Node() {
Name = o.Name,
Image = o.Image,
Symbol = o.Symbol,
KaartNum = o.KaartNum,
children = SortChildren(o.children)
})
.ToList();
}
如果需要,可以将两个方法合并为一个附加的bool sortOnlyByName
参数。