按父级关系对项目排序 [英] Sort Items by parent relationship

查看:71
本文介绍了按父级关系对项目排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自此处,我问自己是否有一种更简单的方法来对像这样的类进行排序

Coming from here I ask myself if there is a easier way to sort a class like

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排序.

So the Items should have the following sort order: sorted first by child-relation and then by the 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.

This question is not about to display data in hierarchical order. It's just about a simpler / not recursive / linq OrderBy / Sort compared to my answer in the linked post.

推荐答案

ParentChild中修复了构造函数后,您应该会发现它可行:

Once you fix the constructor in ParentChild you should find that this works:

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

这给你这个:

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

It is recursive, but at least it is three lines of code. ;-)

仅获取排序结果:

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


稍微干净一点的版本:


A slightly cleaner version:

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

这篇关于按父级关系对项目排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆