I am not sure what you are asking. You seem to be asking how to implement a
plain IEnumerable on a composite structure, but then your example shows a
flat structure using "yield". Your subject makes me infer that you think
foreach is enirely useless for composite structures.
I will address the subject text, because that makes the most sense to me :-)
Take the following class
public class MyTreeNode : IEnumerable<MyT reeNode>
{
public readonly List<MyTreeNode ChildNodes = new List<MyTreeNode >();
public readonly string Name;
public MyTreeNode ParentNode { get; private set; }
public MyTreeNode(MyTr eeNode parentNode, string name)
{
ParentNode = parentNode;
Name = name;
if (parentNode != null)
ParentNode.Chil dNodes.Add(this );
}
public string FullName
{
get
{
if (ParentNode == null)
return Name;
else
return ParentNode.Full Name + "/" + Name;
}
}
public IEnumerator<MyT reeNodeGetEnume rator()
{
foreach (var node in ChildNodes)
{
yield return node;
foreach (var subNode in node)
yield return subNode;
}
}
IEnumerator IEnumerable.Get Enumerator()
{
return GetEnumerator() ;
}
}
}
it can be used like so....
class Program
{
static void Main(string[] args)
{
var tree = new MyTreeNode(null , "Root");
AddChildNodes(t ree, 1, 3);
//********
//NOTE: Foreach not being pretty useless on a composite structure
//********
foreach (var node in tree)
{
Console.WriteLi ne(node.FullNam e);
}
Console.ReadLin e();
}
static void AddChildNodes(M yTreeNode node, int level, int maxLevel)
{
string[] names = new string[] { "A", "B", "C"};
foreach (var name in names)
{
var childNode = new MyTreeNode(node , name);
if (level < maxLevel)
AddChildNodes(c hildNode, level + 1, maxLevel);
}
}
}
and it will output the following.....
Root/A
Root/A/A
Root/A/A/A
Root/A/A/B
Root/A/A/C
Root/A/B
Root/A/B/A
Root/A/B/B
Root/A/B/C
Root/A/C
Root/A/C/A
Root/A/C/B
Root/A/C/C
Root/B
Root/B/A
Root/B/A/A
Root/B/A/B
Root/B/A/C
Root/B/B
Root/B/B/A
Root/B/B/B
Root/B/B/C
Root/B/C
Root/B/C/A
Root/B/C/B
Root/B/C/C
Root/C
Root/C/A
Root/C/A/A
Root/C/A/B
Root/C/A/C
Root/C/B
Root/C/B/A
Root/C/B/B
Root/C/B/C
Root/C/C
Root/C/C/A
Root/C/C/B
Root/C/C/C
Does that prove that foreach is useful for composite structures, or have I
completely missed the point of what you were trying to say?
Regards
Pete