代码之家  ›  专栏  ›  技术社区  ›  DanW

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

  •  2
  • DanW  · 技术社区  · 8 年前
    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 ... 考虑到这种结构,我如何实现返回两条记录 父母亲 属性和特定 儿童 ,而不仅仅是一个 父母亲 有两个 儿童 ?

    例子:

    {
      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 回复  |  直到 8 年前
        1
  •  4
  •   John Wu    8 年前

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

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

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

        2
  •  0
  •   koryakinp    8 年前

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