LINQ: how to get the properties of parent types when retrieving their child collections


I have a set of parent types that contains a list of child 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 already tried (select many) but could not get the ParentType properties.

+6
source share
4 answers
 from p in parents from c in p.Children select new MixedType(...) 

Must work.

+5
source

If I understand what you are going to do, you should use this SelectManay overload , which allows you to call the result selection function for each item in it.

The request 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

+6
source

I believe you are trying to design a MixedType collection from a single ParentType instance

 var parent = new ParentType(); var mixedList = parent.ChildTypes .Select(c => new MixedType { ParentID = parent.ID, ParentName = parent.Name, ChildID = c.ID, ChildName = c.Name }); 
+1
source

If I understand you correctly, you can 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
source

Source: https://habr.com/ru/post/885609/


All Articles