有一个类型为A的列表,每个都包含一个B型列表,什么是获取所有类型B的列表的最佳方法,每个列表都包含它们所属的类型A的列表?
具有如下列表:
var parents = new List<Parent> {
{
new Parent {
ID = 1,
Childs = new List<Child> {
{
new Child {
ID = 1
}
},
{
new Child {
ID = 2
}
},
{
new Child {
ID = 3
}
}
}
}
},
{
new Parent {
ID = 2,
Childs = new List<Child> {
{
new Child {
ID = 3
}
},
{
new Child {
ID = 4
}
},
{
new Child {
ID = 5
}
}
}
}
}
};
我想查询此结果以得到以下结果:
[
{
Child = 1,
InParent = [1]
},
{
Child = 2,
InParent = [1]
},
{
Child = 3,
InParent = [1, 2]
},
{
Child = 4,
InParent = [2]
},
{
Child = 5,
InParent = [2]
},
]
编辑:我尝试过一种方法,首先使用SelectMany
&来使孩子扁平化Distinct
,但是不确定如何再次将其链接到父对象:
var foo =
from childId in parents.SelectMany(x => x.Childs).Select(x => x.ID).Distinct()
select
new
{
childId = childId,
inParent = // Missing Part
};
您必须先使用SelectMany
它们来展平它们,然后使用GroupBy
来按child-id分组并String.Join
合并每个parent-id:
var childParents = parents
.SelectMany(p => p.Childs.Select(c => new {Parent = p, Child = c}))
.GroupBy(x => x.Child.ID)
.Select(g => new
{
Child = g.Key,
InParent = String.Join(", ", g.Select(x => x.Parent.ID))
});
结果:
如果您实际上不希望该InParent
属性是字符串而是一个List<int>
(或数组),请使用以下命令:
.....
InParent = g.Select(x => x.Parent.ID).ToList() // or ToArray()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句