Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ: How to get parent types' properties while getting their children collections

Tags:

c#

linq


I have a collection of parent types that contains a list of children types:


public class ParentType
{

    public int ID;
    public string Name;
    public List<ChildType> ChildTypes { get; set; }

}

public class ChildType
{

    public int ID;
    public string Name;

}

I need to use LINQ to turn them into a collection of the following type:


public class MixedType
{

    public int ParentID;
    public string ParentName;
    public int ChildID;
    public string ChildName;

}

I've already tried (select many) but could not get the ParentType properties.

like image 396
Akram Shahda Avatar asked Apr 10 '11 14:04

Akram Shahda


1 Answers

Provided I understand what you are going to do, you have to use this overload of SelectManay extension which allows you to invoke a result selector function on each element therein.

The query should be:

var lst = new List<ParentType>();

var query = lst.SelectMany(p => p.ChildTypes, 
                                (parent, child) => new { parent, child }
                          )
               .Select(p => new MixedType
                            {
                                ChildID = p.child.ID,
                                ChildName = p.child.Name,
                                ParentID = p.parent.ID,
                                ParentName = p.parent.Name
                            });

Good luck!

like image 97
Homam Avatar answered Sep 20 '22 02:09

Homam