分层排序困难
本文关键字:排序 分层 | 更新日期: 2023-09-27 18:33:42
我遇到了一个非常困难的排序问题,我想知道是否有人可以帮助我解决这个问题。基本上我有一个包含以下信息的SQL表:
ID (The comment's Unique Identifier)
Previous ID (The ID of the comment that is being replied to with this comment)
Position (The position of how "deep" the comment is, a post directly on a
page would be "1" a reply to that "2", etc.
是否可以使用此信息使用 C#/LINQ 进行排序,以便在调用时按正确的顺序返回?
示例如下:
ID | Position | PreviousID | Message|
1 | 1 | 0 | Hello
2 | 1 | 0 | How
3 | 2 | 1 | There!
4 | 2 | 2 | Are
5 | 3 | 4 | You?
将按以下顺序排序:
1. Hello
2. There!
3. How
4. Are
5. You?
我很难弄清楚这将如何完成,或者是否可能,所以我将非常感谢,即使只是朝着正确的方向推动,谢谢!
只是为了了解更多信息,这是一个现有的表格,其中包含大量无法擦除的内容,我只需要找到一种以这种方式对其进行排序的方法。
LINQ 可以使用分层联接对此进行建模
下面是 C# 和 LINQ 中的递归分层联接的示例,并提供了一个简单的演练,可以满足您的需求。
键略有不同,但您应该能够映射到示例。
这更像是一个树遍历问题,而不是一个排序问题。
以下是我的建议:
static IEnumerable<T> PreOrderTraverse<T>(IEnumerable<T> nodes, Func<T, IEnumerable<T>> childrenSelector)
{
foreach (var node in nodes)
{
yield return node;
foreach (var descendant in PreOrderTraverse(childrenSelector(node), childrenSelector))
{
yield return descendant;
}
}
}
static void Main(string[] args)
{
/* Some code to load comments*/
var children = comments.ToLookup(c => c.PreviousID);
var result = PreOrderTraverse(children[0], c => children[c.ID]);
foreach (var comment in result)
{
Console.WriteLine(comment.Message);
}
}