473,796 Members | 2,537 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Re: foreach pretty useless for composite classes, don't ya thunk?

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
Sep 20 '08 #1
4 2566
On Sep 20, 4:14*am, "Peter Morris" <mrpmorri...@SP AMgmail.comwrot e:
>
Does that prove that foreach is useful for composite structures, or have I
completely missed the point of what you were trying to say?
Thanks; this was a good example that I've saved to study. Seems a
couple of things are new to me (I've never seen readonly for a list,
only for primitive data like an int, but I guess it makes sense;
likewise 'var' sounds like Visual Basic but it's C#3 compliant I
think), but the main point is that for a "composite" structure (where
I take it a class contains another class as member) uses 'foreach' but
implicitly uses the properties of collections themselves for the
member variable.

To wit:

public IEnumerator<MyT reeNodeGetEnume rator()
{
foreach (var node in ChildNodes)
{
yield return node;
foreach (var subNode in node)
yield return subNode;
}
}

makes use of the property of public readonly List<MyTreeNode >
ChildNodes = new List<MyTreeNode >();
that "List" is a generic container that has its own "behind the
scenes" iterator.

However, as I type this I see that two yield returns are present, but,
I've seen this before and it's legal.

Bottom line: foreach is a useful tool, and once I study this example
more I'll have more to say perhaps, but it's not clear you are really
using 'foreach' any different from the way I currently use it: to
iterate member variables (even classes) that are parts of generic
containers (from the collections library) like List<MyTreeNode >
ChildNodes = new List<MyTreeNode >();

Or maybe that's how you are supposed to use foreach, since these
containers have 'foreach' built in, behind the scenes. Anyway more
later.

RL
Sep 20 '08 #2
couple of things are new to me (I've never seen readonly for a list,
only for primitive data like an int, but I guess it makes sense;
Just saves its reference from changing :-)

likewise 'var' sounds like Visual Basic but it's C#3 compliant
It's just shorthand for writing the class name out twice. I only use it
where it is obvious what the type is.

>However, as I type this I see that two yield returns are present, but,
I've seen this before and it's legal.
yield return 1;
yield return 3;
yield return 5;
yield return 7;

That's legal too, but not much use :-)

>>
Bottom line: foreach is a useful tool, and once I study this example
more I'll have more to say perhaps, but it's not clear you are really
using 'foreach' any different from the way I currently use it:
<<

You *never* use "foreach" differently. "foreach" is just a language
specific way of comsuming the iterator pattern, "yield" is a language
specific way of implementing the iterator pattern. The purpose of the
iterator pattern is to allow you to get access to all *relevant* items in
turn, and not to worry about how those values are obtained. An example is
to get each word within a document for spell checking; these words are held
within various containers (a word, within a paragraph, within a cell, within
a table row, within a table, within a column, within a page, within a
document) - you wouldn't want to write code to loop through all of those,
you just want to iterate all words within the document.
>>
Or maybe that's how you are supposed to use foreach, since these
containers have 'foreach' built in, behind the scenes. Anyway more
later.
<<

Yep. As I just said above, foreach is a consumer of the iterator pattern,
nothing more.

Pete

Sep 20 '08 #3
OK, I am beginning to see now, thanks Peter Morris.

But one more thing: can you tell me how to get rid of this compiler
error?:

foreach statement cannot operate on variables of type
'IEnumerableEx0 1.Namer' because it implements multiple instantiations
of System.Collecti ons.Generic.IEn umerable<T>'; try casting to a
specific interface instantiation

See the code I will post to Family Tree Mike's reply (since it's his
code, modified).

Almost there (for me), I appreciate it.

BTW your example was good for a n-ary tree that is traversed 'depth
first' recursively rather than 'breath first', and I've put it in my
library as such; thanks again. I already have (from my own work) a
'breath first' non-recursive n-ary tree, so this complements that.

RL

Peter Morris wrote:
>
Yep. As I just said above, foreach is a consumer of the iterator pattern,
nothing more.
Sep 20 '08 #4
On Sep 20, 4:16*pm, raylopez99 <raylope...@yah oo.comwrote:
BTW your example was good for a n-ary tree that is traversed 'depth
first' recursively rather than 'breath first', and I've put it in my
library as such; thanks again. *I already have (from my own work) a
'breath first' non-recursive n-ary tree, so this complements that.
Exactly. And that leads to the next big advantage of the iterator/
enumerator pattern. The collection class itself encapsulates the
logic required to enumerate it's items.
Sep 21 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
1440
by: Matan Nassau | last post by:
This question is a little embarrassing... I have a boolean expressions interpreter with its composite (see Go4's "Design Patterns" book). here is a simple leaf of the composite: class Constant : public BooleanExp { public: Constant(bool); virtual ~Constant(); virtual void Accept(BooleanExpVisitor&);
0
1459
by: Michael Andersson | last post by:
Given a set of classes class A { enum [ ID = 0x0001} }; class B { enum [ ID = 0x0002} }; class B { enum [ ID = 0x0004} }; I wish to generate a composite class, perhaps using something like Alexandrescu's typelists (pseudo-code:)
32
4157
by: James Curran | last post by:
I'd like to make the following proposal for a new feature for the C# language. I have no connection with the C# team at Microsoft. I'm posting it here to gather input to refine it, in an "open Source" manner, and in an attempt to build a ground-swell of support to convince the folks at Microsoft to add it. Proposal: "first:" "last:" sections in a "foreach" block The problem: The foreach statement allows iterating over all the...
13
2002
by: cody | last post by:
foreach does implicitly cast every object in the collection to the specified taget type without warning. Without generics this behaviour had the advantage of less typing for us since casting was neccessary in nearly every collection. But with generics I consider this feature of foreach as dangerous. Casting is now almost always unwanted. interface IFoo{} class Foo:IFoo{} class FooBar:IFoo{}
104
7204
by: cody | last post by:
What about an enhancement of foreach loops which allows a syntax like that: foeach(int i in 1..10) { } // forward foeach(int i in 99..2) { } // backwards foeach(char c in 'a'..'z') { } // chars foeach(Color c in Red..Blue) { } // using enums It should work with all integral datatypes. Maybe we can step a bit further: foeach(int i in 1..10, 30..100) { } // from 1 to 10 and 30 to hundred
14
1811
by: Josh Ferguson | last post by:
I don't believe a syntax driven equivalent exists for this, but I just thought it would be neat if you could use foreach to do something like this: foreach (Object x in collection1, collection2) and have it sequentially enumerate through both of them.
10
2964
by: fig000 | last post by:
HI, I'm new to generics. I've written a simple class to which I'm passing a generic list. I'm able to pass the list and even pass the type of the list so I can use it to traverse it. It's a generic list of business objects. I'm able to see that the type is the correct one in the debugger. However when I try to traverse the list using the type I can't compile. The same type variable I've verified as being passed
8
1435
by: =?Utf-8?B?RmFtaWx5IFRyZWUgTWlrZQ==?= | last post by:
An example of a slightly more complicated class might be to have a collection of first names, and a collection of last names in your class. The IEnumerable functions then could return the complete set of all possible combinations of first and last name.
8
273
by: Bill Butler | last post by:
"raylopez99" <raylopez99@yahoo.comwrote in message news:bd59f62a-5b54-49e8-9872-ed9aef676049@t54g2000hsg.googlegroups.com... <snip> I don't think "right" is the correct word. There are many other words that could fill in the blank though. "Or am I _______ as usual?"
0
10457
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10231
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10013
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7550
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5443
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5576
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4119
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3733
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2927
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.