, LINQ , , , - ( , foreach).
:
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" }
};
var parentsWithChildren = parents.Select(x => new Parent
{
ParentName = x.ParentName,
ChildNames = children
.Where(c => c.ParentName == x.ParentName)
.Select(c => c.ChildName)
});
foreach (var parent in parentsWithChildren)
{
var childNamesConcentrated = string.Join(",", parent.ChildNames);
var childNames = string.IsNullOrWhiteSpace(childNamesConcentrated)
? "(empty)" : childNamesConcentrated;
Console.WriteLine("Parent = {0}, Children = {1}", parent.ParentName, childNames);
}
Parent parents, ChildNames. Parent .