在LINQ中订购自引用层次结构 [英] Ordering a self-referencing hierarchy in LINQ
问题描述
我有一个名为NavigationElement
的类,看起来像这样
I have a class called NavigationElement
that looks like this
public class NavigationElement
{
public int Id { get; set; }
public string Title { get; set; }
public string Link { get; set; }
public int SortOrder { get; set; }
public bool Visible { get; set; }
public int? ParentId { get; set; }
public virtual ICollection<NavigationElement> Children { get; set; }
public virtual NavigationElement Parent { get; set; }
public NavigationElement()
{
Children = new List<NavigationElement>();
}
}
如您所见,该类是自引用的.由此,我创建了一个带有下拉菜单(正在播放层次结构)的网站导航菜单.
As you can see, the class is self referencing. From that, I am creating a site navigation menu with drop downs (hierarchy in play).
我在订购物品方面很挣扎.我希望通过SortOrder
属性对顶层项进行排序,但是其下的所有内容,我希望通过Title
属性对按字母顺序进行排序.
I am struggling in the ordering of the items. I want the top-level items to be ordered by the SortOrder
property, but everything underneath, I would like ordered alphabetically by the Title
property.
这就是我到目前为止所做的原因.
Here is why I have done so far.
var orderedModel = unorderedModel.OrderBy(x => x.SortOrder).ThenBy(x => x.Children.OrderBy(y => y.Title).ThenBy(z => z.Children.OrderBy(a => a.Title))).ToList();
unorderedModel
的类型为List<NavigationElementModel>
.
这正在编译,但是运行代码时出现错误.错误提示:
This is compiling, but I get an error when I run the code. The error says:
至少一个对象必须实现IComparable.
At least one object must implement IComparable.
推荐答案
您应该对所有子元素进行递归并对其进行排序.
You should just go recursive through all children elements and sort it.
类似:
var ordered = unorderedModel.OrderBy(x=>x.SortOrder).ToList();
ordered.ForEach(OrderChildren);
public void OrderChildren(NavigationElement el)
{
el.Children = el.Children.OrderBy(x => x.Title).ToList();
if (el.Children != null)
{
foreach (var c in el.Children)
{
OrderChildren(c);
}
}
}
这篇关于在LINQ中订购自引用层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!