开发者

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


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 coul开发者_C百科d not get the ParentType properties.


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!


from p in parents
from c in p.Children
select new MixedType(...)

Should work.


I believe you are trying to project a collection of MixedType out of one instance of ParentType

var parent = new ParentType();

var mixedList = parent.ChildTypes
                  .Select(c => new MixedType
                  {
                     ParentID = parent.ID,
                     ParentName = parent.Name,
                     ChildID = c.ID,
                     ChildName = c.Name

                  });


If I understand you correctly, you could try something like this:

var mixed = 
    from child in parent.ChildTypes 
    select new MixedType 
    { 
        ParentID = parent.ID,
        ParentName = parent.Name,
        ChildID = child.ID, 
        ChildName = child.Name
    };
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜