CSharp · Console
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
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; }
}
public class Program
{
public static void Main(string[] args)
{
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"}
};
///////////////////////////////////////////////
// Technique #1:
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);
}
Display("Technique #1:", parents);
///////////////////////////////////////////////
///////////////////////////////////////////////
// Technique #2:
var parentChildPairs =
from p in parents
join c in children on p.ParentName equals c.ParentName into childList
select new { Parent = p, ChildrenNames = childList.Select(c => c.ChildName) };
foreach (var dzp in parentChildPairs)
{
var p = dzp.Parent;
var c = dzp.ChildrenNames; // to avoid foreach closure side-effects
p.ChildNames = c;
}
Display("Technique #2:", parentChildPairs.Select(p => p.Parent));
///////////////////////////////////////////////
///////////////////////////////////////////////
// Technique #3:
parents.ForEach(p => p.ChildNames = children.Where(c => c.ParentName == p.ParentName).Select(c => c.ChildName).ToList());
Display("Technique #3:", parents);
///////////////////////////////////////////////
///////////////////////////////////////////////
// Technique #4:
var clu = children.ToLookup(c => c.ParentName, c => c.ChildName);
parents.ForEach(p => p.ChildNames = clu[p.ParentName]);
Display("Technique #4:", parents);
///////////////////////////////////////////////
}
static void Display(string message, IEnumerable<Parent> parents)
{
Console.WriteLine(message);
foreach (var p in parents)
{
var childNames = string.Join(",", p.ChildNames);
Console.WriteLine("Parent = {0}, Children = {1}", p.ParentName, childNames);
}
Console.WriteLine("");
}
}
}