(Full code available at: https://dotnetfiddle.net/tdKNgH)
I have two lists that are associated by ParentName
and I would like to join them in a specific way.
class Parent
{
public string ParentName { get; set; }
public IEnumerable<string> ChildNames { get; set; }
}
class Child
{
public string ParentName { get; set; }
public string ChildName { get; set; }
}
var parents = new List<Parent>()
{
new Parent() {ParentName = "Lee"},
new Parent() {ParentName = "Bob"},
new Parent() {ParentName = "Tom"}
};
var children = new List<Child>()
{
new Child() {ParentName = "Lee", ChildName = "A"},
new Child() {ParentName = "Tom", ChildName = "B"},
new Child() {ParentName = "Tom", ChildName = "C"}
};
I'm using a foreach loop to join, and it works, but is there a more succinct way to do it?
foreach (var parent in parents)
{
var p = parent; // to avoid foreach closure side-effects
p.ChildNames = children.Where(c => c.ParentName == p.ParentName)
.Select(c => c.ChildName);
}
Here's what the resulting parents list would look like:
Parent Children
------ --------
Lee A
Bob (empty)
Tom B,C