【问题标题】:Sort Items by parent relationship按父关系排序项目
【发布时间】:2016-11-20 15:23:34
【问题描述】:

来自here 我问自己是否有更简单的方法来对类进行排序

public class ParentChild
{
    int ID { get; set; }
    int ParentID { get; set; }

    public ParentChild(int id, int pid)
    {
        ID = id;
        ParentID = pid;
    }
}

取决于它的父母关系。

例如

List<ParentChild> pcItems = new List<ParentChild>()
{           
    new ParentChild(1,0), // 0 is the default value in case of no parent
    new ParentChild(2,1),
    new ParentChild(3,2),
    new ParentChild(4,2),
    new ParentChild(5,1),
    new ParentChild(6,4),
    new ParentChild(7,1),
    new ParentChild(8,6),
    new ParentChild(9,3)
};

因此,项目应具有以下排序顺序:首先按子关系排序,然后按 ID。

1       // root
+-2
| +-3
| | +-9 // is the child of 3
| | 4   //is the 2nd child of 2 and has the higher ID conmpared to 3
| | +-6
| |   +-8
| 5
7

本题不打算按层次顺序显示数据。与我在链接帖子中的答案相比,这只是一个更简单/非递归/linq OrderBy / Sort

【问题讨论】:

  • “我在链接的帖子中有一个工作方法,所以不需要努力” -- 是的,有。每个 Stack Overflow 问题都需要独立存在,因此如果相关问题被删除,问题仍然有意义。

标签: c# class sorting


【解决方案1】:

一旦你修复了ParentChild 中的构造函数,你应该会发现这是可行的:

var lookup = pcItems.ToLookup(x => x.ParentID, x => x.ID);

Func<int, int, IEnumerable<string>> build = null;
build = (pid, level) =>
    lookup[pid]
        .SelectMany(id =>
            new [] { "".PadLeft(level * 4) + id.ToString() }
            .Concat(build(id, level + 1)));

IEnumerable<string> results = build(0, 0);

这给了你这个:

它是递归的,但至少它是三行代码。 ;-)


只得到一个排序的结果:

var lookup = pcItems.ToLookup(x => x.ParentID, x => x.ID);
Func<int, int, IEnumerable<ParentChild>> build = null;
build = (pid, level) => lookup[pid]
                        .SelectMany(id => new[] { pcItems.Single(x => x.ID == id) }
                        .Concat(build(id, level + 1)));
IEnumerable<ParentChild> results = build(0, 0);

稍微干净一点的版本:

var lookup = pcItems.ToLookup(x => x.ParentID);

Func<int, int, IEnumerable<ParentChild>> build = null;
build = (pid, level) =>
    lookup[pid].SelectMany(pc => new[] { pc }.Concat(build(pc.ID, level + 1)));

IEnumerable<ParentChild> results = build(0, 0);

【讨论】:

  • @fubo - 您刚刚在树输出中添加了行。这有点繁琐。
  • 忘掉那些行,这只是关于排序
  • @fubo - 够了。我想你会发现你需要递归来获得正确的排序顺序。
  • 我在您的答案中添加了我的修改 - 随时回滚
  • @fubo - 我在你的代码下添加了一个稍微干净的版本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-08
  • 2019-05-14
  • 2016-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多