[英]Group list of objects with corresponding child with multiple inheritance using LINQ
我将使用更简单的对象来总结问题。 我也相信这不是一个重复的问题。
我有一个 Type1 的平面 IEnumerable 需要转换为 Type2 的 IEnumerable,其中每个 object 都包含一个 IEnumerable 的子级。 我正在使用 AutoMapper,所以从 Type1 到 Type2 的映射不是问题。 问题是每个孩子都可能有自己的孩子,而那些孙辈也可能有自己的孩子。
public class Type1
{
public int? ParentId { get; set; }
public int Id { get; set; }
...other properties
}
public class Type2
{
public int Id { get; set; }
public IEnumerable<Type2> Children { get; set; }
...other properties
}
IEnumerable<Type1> source = GetItems();
IEnumerable<Type2> result = ...someLinqExpression....;
是否可以使用 linq 来“取消扁平化”列表并将孩子分组? 或者是否有替代使用具有良好性能和可读性的 linq 的替代方法?
这是我到目前为止所拥有的:
var parents = source
.Where(element => element.ParentId == null);
source = source.Except(parents);
parents
.Select(element => Mapper.Map<Type2>(element))
.ToList()
.ForEach(parent =>
parent.Children = source
.Where(child => child.ParentId == parent.Id)
.Select(child => Mapper.Map<Type2>(child)));
您应该能够通过编写递归 function 来做到这一点,类似于
public IEnumerable<Type2> RecursiveBuildHierarchy(IEnumerable<Type1> parents, IEnumerable<Type1> entireList)
{
var type2Parents = parents.Select(element => Mapper.Map<Type2>(element));
foreach(var parent in type2Parents)
{
parent.Children = RecursiveBuildHierarchy(entireList.Where(x => x.ParentId = parent.Id), entireList);
}
return type2Parents;
}
你会开始:
IEnumerable<Type1> source = GetItems();
IEnumerable<Type2> result = RecursiveBuildHierarchy(source.Where(x => x.ParentId == null), source);
可能有一些很好的方法可以让它直接与你的映射库一起工作。 我个人发现在映射后改变属性的想法有点“代码味道”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.