【发布时间】:2014-02-27 15:04:35
【问题描述】:
我有一个必须由父母订购的产品列表,然后是该父母的所有孩子,然后是下一个父母,等等。
Product One
Child One
Child Two
Product Two
Child One
这些产品都在一个带有父 id 字段的表中,子产品有一个父 id,但父项可以有一个空父项(表示该产品是顶级产品)
我在想类似以下的事情:
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);
}
有什么建议可以让我更干净一点吗?
【问题讨论】: