C#Linq IQueryable选择扁平嵌套对象列表

问题描述 投票:2回答:2
public class Parent
{
    public int ParentId { get; set; }
    public string ParentPropertyA { get; set; }
    public string ParentPropertyA { get; set; }
    public List<Child> Children{get; set;}

}

public class Child
{
    public int ChildId { get; set; }
    public string ChildPropertyA { get; set; }
    public string ChildPropertyB { get; set; }
}

private static Expression<Func<Parent, dynamic>> BuildModel()
{
    return x => new
    {
        x.ParentId,
        x.Children
    };
}

我在IQueryable.Select(BuildModel())上使用这个表达式

假设我有一个带有两个ParentChildren对象......鉴于这个结构我怎么能用所有Parent属性和特定的Children返回两个记录,而不是只有一个Parent和两个Children

例:

{
  ParentId: 1,
  ParentPropertyA: "parentA",
  ParentPropertyB: "parentB",
  Children:
  [
    {
      ChildId: 1,
      ChildPropertyA: "childA1",
      ChildPropertyB: "childB1"
    },
    {
      ChildId: 2,
      ChildPropertyA: "childA2",
      ChildPropertyB: "childB2"
    }
  ]
}

相反,我想让他们返回:

[
  {
    ParentId: 1,
    ParentPropertyA: "parentA",
    ParentPropertyB: "parentB",
    ChildId: 1,
    ChildPropertyB: "childB1"
  },
  {
    ParentId: 1,
    ParentPropertyA: "parentA",
    ParentPropertyB: "parentB",
    ChildId: 2,
    ChildPropertyB: "childB2"
  }
]

这可能吗?谢谢!

c# linq iqueryable
2个回答
4
投票

在父集合上使用SelectMany。在SelectMany表达式中,选择子项,并将其与父项的副本配对。

var flattenedList = parents.SelectMany
(
    p => p.Children.Select
    (
        c => new { Parent = p, Child = c } 
    )
);

这将为每个孩子提供一个元素,根据需要复制父母。


0
投票

DTO课程:

public class DTO
{
   public int ParentId { get; set; }
   public string ParentPropertyA { get; set; }
   public string ParentPropertyB { get; set; }
   public int ChildrenId { get; set; }
   public string ChildrenPropertyB { get; set; }
}

用法:

var parent = GetParent() //Get Parent instance

List<Dto> dtos = parent.Childrens.Select(q => new DTO
{
    ParentId = parent.ParentId,
    ParentPropertyA = parent.ParentPropertyA
    ParentPropertyB = parent.ParentPropertyB,
    ChildrenId = q.ChildrenId,
    ChildrenPropertyB = q.ChildrenPropertyB
})
.ToList();
© www.soinside.com 2019 - 2024. All rights reserved.