I would also use the extension method approach, but use the iterator method:
public static class BoxEx
{
public static IEnumerable<Box> Flatten(this Box box)
{
yield return box;
if (box.Contents != null)
{
foreach (var b in box.Contents.SelectMany(b2 => Flatten(b2)))
{
yield return b;
}
}
}
}
Your method FindBoxBySizewill now look like this:
Box FindBoxBySize(Box box, BoxSize size)
{
return (from b in box.Flatten()
where b.Size == size
select b).FirstOrDefault();
}
The original call code works without changes:
var small = FindBoxBySize(box, BoxSize.Small);
source
share