【问题标题】:Difficult hierarchical Sorting困难的分层排序
【发布时间】:2013-10-08 09:37:21
【问题描述】:

我遇到了一个非常困难的排序问题,我想知道是否有人可以帮助我解决这个问题。基本上我有一个充满以下信息的 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?

我无法弄清楚如何做到这一点,或者是否有可能,所以即使只是朝着正确的方向轻推,我也将不胜感激,谢谢!

只是为了获得更多信息,这是一个现有的表格,其中包含大量无法删除的内容,我只需要找到一种方法以这种方式对其进行排序。

【问题讨论】:

标签: c# sql linq sorting


【解决方案1】:

LINQ 可以使用分层连接对此进行建模

这里是Recursive Hierarchical Joins in C# and LINQ 的示例,并提供了一个简单的演练,可以满足您的需求。

键略有不同,但您应该能够映射到示例。

【讨论】:

    【解决方案2】:

    这更像是一个树遍历问题而不是排序问题。

    这是我的推荐:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-17
      • 2017-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-03
      • 1970-01-01
      相关资源
      最近更新 更多