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

时间:2018-02-28 21:28:48

标签: c# linq iqueryable

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())

上使用此表达式

我们说我有Parent个对象,其中有两个Children ... 鉴于该结构,我如何实现返回包含所有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"
  }
]

这可能吗?谢谢!

2 个答案:

答案 0 :(得分:4)

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

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

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

答案 1 :(得分: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();