父项和子项的订单列表 [英] Order list by parent and child items

查看:448
本文介绍了父项和子项的订单列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我列出了必须由父级订购的产品列表,然后是该父级的所有子级,然后是下一个父级,等等.

I have a list of products that have to be ordered by parent then all children of that parent, then next parent, etc.

Product One
    Child One
    Child Two
Product Two
    Child One

这些产品都在一个表中并带有一个父ID字段,子产品具有一个父ID,但是父项可以具有一个空父项(表明该产品是顶级产品)

These products are all in one table with a parent id field, the child products have a parent id but the parent items can have a null parent (indicating that product is a top level product)

我在想以下内容:

var list = GetProductList();
var newList = new List<ProductDTO>();

var parents = from p in list
    where p.Parent == null
    select p.Id;


foreach (var parent in parents)
{
    var tempList = new List<ProductDTO>();
    tempList.Add(list.FirstOrDefault(x => x.Id == parent));
    tempList.AddRange(list.Where(x => x.Parent == parent).OrderBy(x => x.Id));
    newList.AddRange(tempList);
}

关于我将如何做得更清洁的任何建议?

Any suggestions on how I would do this a little cleaner?

推荐答案

给出父项"是可为空的属性(此处假定为可为null的int).以下应为您提供与父子相关的有序列表:

Given "Parent" is nullable property (assuming nullable int here). Following should give you parent-child related ordered list:

 public class ProductDTO
 {
     public int Id { get; set; }
     public string Name { get; set; }
     public int? Parent { get; set; }
 }

 var products = new List<ProductDTO>();
 products.Add(new ProductDTO() { Id = 1, Name = "Product One" });
 products.Add(new ProductDTO() { Id = 2, Name = "Product Two" });
 products.Add(new ProductDTO() { Id = 3, Name = "Product Three" });
 products.Add(new ProductDTO() { Id = 4, Name = "Child One", Parent=1 });
 products.Add(new ProductDTO() { Id = 5, Name = "Child Two", Parent = 2 });
 products.Add(new ProductDTO() { Id = 6, Name = "Child One", Parent = 1 });

var ordered = products
                .Where(p => p.Parent == null)
                .OrderBy(p=> p.Id)
                .Select(p => products
                    .Where(c => c.Parent == p.Id)
                    .OrderBy(c => c.Id))
                .ToList();

这篇关于父项和子项的订单列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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