473,653 Members | 2,972 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

recursive GetEnumerator()

Hi,
is it possible to have a recursive GetEnumerator for traversing a tree
structure ?

public IEnumerator<DTy peGetEnumerator ()

{

return GetEnumerator(r oot);

}

public IEnumerator<DTy peGetEnumerator (node p)

{

if(p.low!=null)

GetEnumerator(p .low);

yield return p.val;

if(p.high!=null )

GetEnumerator(p .high);

}

compiles ok, but foreach only does 1 iteration.

Colin =^.^=

Jun 24 '07 #1
16 4261
"colin" <co*********@nt world.NOSPAM.co mwrote in message
news:VB******** ********@newsfe 6-win.ntli.net...
Hi,
is it possible to have a recursive GetEnumerator for traversing a tree
structure ?

public IEnumerator<DTy peGetEnumerator ()

{

return GetEnumerator(r oot);

}

public IEnumerator<DTy peGetEnumerator (node p)

{

if(p.low!=null)

GetEnumerator(p .low);

yield return p.val;

if(p.high!=null )

GetEnumerator(p .high);

}

compiles ok, but foreach only does 1 iteration.

Colin =^.^=
ah not to worry, i did the recursion by using recursive foreach instead of
the function call.

Colin =^.^=
Jun 24 '07 #2
colin wrote:
Hi,
is it possible to have a recursive GetEnumerator for traversing a tree
structure ?

public IEnumerator<DTy peGetEnumerator ()

{

return GetEnumerator(r oot);

}

public IEnumerator<DTy peGetEnumerator (node p)

{

if(p.low!=null)

GetEnumerator(p .low);
The GetEnumerator method returns an enumerator. If you just throw away
the return value, there is hardly any reason to make the call, is there.
yield return p.val;
Why is the code continuing after return? Did you ignore the compiler
warning about unreachable code?
if(p.high!=null )

GetEnumerator(p .high);
Once again, mind the return value.
}

compiles ok, but foreach only does 1 iteration.
You mean that it compiles, but with warnings...

--
Göran Andersson
_____
http://www.guffa.com
Jun 24 '07 #3
"Göran Andersson" <gu***@guffa.co mwrote in message
news:er******** ******@TK2MSFTN GP05.phx.gbl...
colin wrote:
>Hi,
is it possible to have a recursive GetEnumerator for traversing a tree
structure ?

public IEnumerator<DTy peGetEnumerator ()

{

return GetEnumerator(r oot);

}

public IEnumerator<DTy peGetEnumerator (node p)

{

if(p.low!=null )

GetEnumerator( p.low);

The GetEnumerator method returns an enumerator. If you just throw away the
return value, there is hardly any reason to make the call, is there.
I dont think in this case it actually returns anything, at least not thats
used.
if I try and return an IEnumerator it complains.
>
>yield return p.val;

Why is the code continuing after return? Did you ignore the compiler
warning about unreachable code?
thats the nature of yield I beleive, however this is the first time ive used
it,
so im a bit unsure, but it seems it just yields control, doesnt actually
realy return.
ie when it comes accros a 'yield return expresion' it executs
the code inside the foreach loop with the value in expresion
when that code has executed, it continues after the 'yield return expresion'
statement
>
>if(p.high!=nul l)

GetEnumerator( p.high);

Once again, mind the return value.
its recursive so the value isnt used from the return as such, but from the
yield statement.
>compiles ok, but foreach only does 1 iteration.

You mean that it compiles, but with warnings...
dont think there were any warnings at all,
however ive since used foreach instead of calling another GetEnumerator
and it works ok...

so getenumerator does foreach wich calls getenumerator and does foreach
recursivly for all the trees nodes.

Colin =^.^=
Jun 24 '07 #4
Hi,

I had to implement in in C# 3.0. There is nothing very C# 3.0 special there,
so you can easily translate it back to C# 2.0.

public static IEnumerable<TTr averseTree<T>(t his IEnumerable<Tse lf,
Func<T, IEnumerable<T>g etChildren)
{
var parents = new Stack<IEnumerat or<T>>();
var enumerator = self.GetEnumera tor();
parents.Push(en umerator);
do
{
enumerator = parents.Pop();
while (enumerator.Mov eNext())
{
var current = enumerator.Curr ent;

yield return current;

parents.Push(en umerator);
enumerator = getChildren(cur rent).GetEnumer ator();
}
}
while (parents.Count 0);
}

If you know your types you may replace getChildren with your actual method
that returns enumerator of node children.

-yuriy
http://couldbedone.blogspot.com

"Göran Andersson" <gu***@guffa.co mwrote in message
news:er******** ******@TK2MSFTN GP05.phx.gbl...
>colin wrote:
>>Hi,
is it possible to have a recursive GetEnumerator for traversing a
tree
structure ?
public IEnumerator<DTy peGetEnumerator ()

{

return GetEnumerator(r oot);

}

public IEnumerator<DTy peGetEnumerator (node p)

{

if(p.low!=nul l)

GetEnumerator (p.low);
The GetEnumerator method returns an enumerator. If you just throw
away the return value, there is hardly any reason to make the call,
is there.
I dont think in this case it actually returns anything, at least not
thats
used.
if I try and return an IEnumerator it complains.
>>yield return p.val;
Why is the code continuing after return? Did you ignore the compiler
warning about unreachable code?
thats the nature of yield I beleive, however this is the first time
ive used
it,
so im a bit unsure, but it seems it just yields control, doesnt
actually
realy return.
ie when it comes accros a 'yield return expresion' it executs
the code inside the foreach loop with the value in expresion
when that code has executed, it continues after the 'yield return
expresion'
statement
>>if(p.high!=nu ll)

GetEnumerator (p.high);
Once again, mind the return value.
its recursive so the value isnt used from the return as such, but from
the yield statement.
>>compiles ok, but foreach only does 1 iteration.
You mean that it compiles, but with warnings...
dont think there were any warnings at all,
however ive since used foreach instead of calling another
GetEnumerator
and it works ok...
so getenumerator does foreach wich calls getenumerator and does
foreach recursivly for all the trees nodes.

Colin =^.^=

Jun 24 '07 #5
"Yuriy Solodkyy" <y.************ @gmail.comwrote in message
news:8a******** *************** ****@msnews.mic rosoft.com...
Hi,

I had to implement in in C# 3.0. There is nothing very C# 3.0 special
there, so you can easily translate it back to C# 2.0.

public static IEnumerable<TTr averseTree<T>(t his IEnumerable<T>
self, Func<T, IEnumerable<T>g etChildren)
{
var parents = new Stack<IEnumerat or<T>>();
var enumerator = self.GetEnumera tor();
parents.Push(en umerator);
do
{
enumerator = parents.Pop();
while (enumerator.Mov eNext())
{
var current = enumerator.Curr ent; yield return current;

parents.Push(en umerator);
enumerator = getChildren(cur rent).GetEnumer ator();
}
}
while (parents.Count 0);
}

If you know your types you may replace getChildren with your actual method
that returns enumerator of node children.
I was hoping to do it recursivly rather than remember all the parent nodes
for each entry.
I think its a bit simpler and could be faster,
however ive no idea how this looks in actual implementaion.

I made the nodes themselves enumerable thus :-

public IEnumerator<DTy peGetEnumerator ()
{
if (low != null)
foreach (DType x in low)
yield return x;
yield return val;
if (high != null)
foreach (DType x in high)
yield return x;
}

sp the main class GetEnumerator just calls foreach on the root node.

I confess to not fully understanding what im doing however,
I picked up a bit from examples, although the recursive took a while to
figure out.
ive ignored the MoveNext and Current as it doesnt fit with doing it
recursivly.
im not sure if Il need it anyway, but it seems to work ok.

I got realy confused with the difference between interfaces and
generic/non-generic bases etc.

Colin =^.^=
Jun 25 '07 #6
colin wrote:
I dont think in this case it actually returns anything, at least not thats
used.
if I try and return an IEnumerator it complains.
Yes, it does return an enumerator. (Or, at least, it works as if it
returns an enumerator. I don't know exactly how it's implemented.)
>>yield return p.val;
Why is the code continuing after return? Did you ignore the compiler
warning about unreachable code?

thats the nature of yield I beleive,
Yes, you are right. The code continues at that point for the next step
in the enumeration.

--
Göran Andersson
_____
http://www.guffa.com
Jun 25 '07 #7
"Göran Andersson" <gu***@guffa.co mwrote in message
news:%2******** ********@TK2MSF TNGP03.phx.gbl. ..
colin wrote:
>I dont think in this case it actually returns anything, at least not
thats used.
if I try and return an IEnumerator it complains.

Yes, it does return an enumerator. (Or, at least, it works as if it
returns an enumerator. I don't know exactly how it's implemented.)
it seems to actually return the data not the enumerator,
well it complains if you do,
I gues IEnumerator is just a sort of keyword to say its not a normal
function.

im not sure what happens if you actually return data without yield,
wether it gets called for each element, I gues thats what the Next and
Current would be for.

Colin =^.^=
Jun 25 '07 #8
On Jun 25, 12:04 pm, "colin" <colin.ro...@nt world.NOSPAM.co mwrote:
Yes, it does return an enumerator. (Or, at least, it works as if it
returns an enumerator. I don't know exactly how it's implemented.)

it seems to actually return the data not the enumerator,
well it complains if you do,
I gues IEnumerator is just a sort of keyword to say its not a normal
function.
No, not at all. GetEnumerator returns an enumerator. That enumerator
is then used to fetch an IEnumerable, which has the MoveNext and
Current members.

foreach does all this for you under the hood.
im not sure what happens if you actually return data without yield,
wether it gets called for each element, I gues thats what the Next and
Current would be for.
yield return is just smart syntactic sugar which builds an IEnumerator/
IEnumerable.
You can use ildasm or reflector to see what types are in your compiled
code.

It's worth understanding what foreach does before you embark on C# 2's
iterator-building features.

Jon

Jun 25 '07 #9
"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote in message
news:11******** **************@ c77g2000hse.goo glegroups.com.. .
On Jun 25, 12:04 pm, "colin" <colin.ro...@nt world.NOSPAM.co mwrote:
Yes, it does return an enumerator. (Or, at least, it works as if it
returns an enumerator. I don't know exactly how it's implemented.)

it seems to actually return the data not the enumerator,
well it complains if you do,
I gues IEnumerator is just a sort of keyword to say its not a normal
function.

No, not at all. GetEnumerator returns an enumerator. That enumerator
is then used to fetch an IEnumerable, which has the MoveNext and
Current members.

foreach does all this for you under the hood.
>im not sure what happens if you actually return data without yield,
wether it gets called for each element, I gues thats what the Next and
Current would be for.

yield return is just smart syntactic sugar which builds an IEnumerator/
IEnumerable.
You can use ildasm or reflector to see what types are in your compiled
code.

It's worth understanding what foreach does before you embark on C# 2's
iterator-building features.
thanks,

well im only using foreach on this tree to check the rest of it is working,
so I dont intend to make it too elaborate,
like i said before, the current and move next arnt very usefull in a tree,
unless the parent nodes are stored as well wich is messy.
with recursive calls they are stored but on the call stack.

I dont think I will be needing to use the iterator outside a foreach loop,
so I think im safe.

I think its realy quite neat you can use foreach to iterate a list like
this,
before in c++ I had to pass a function and all other data it needed to an
iterator,
and wich made it a bit more limited.
the complexity of the many different types that have to do with collections
however has overflowed my brain for now,
im not even sure if I realy need to inherit any of them,
the complexities of extracting nodes in a tree
and balancing it is enough to cope with for 1 day.

Colin =^.^=
Jun 25 '07 #10

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

Similar topics

1
4914
by: Kevin P. Fleming | last post by:
ArrayList implements an overload for IEnumerator's GetEnumerator method as follows: GetEnumerator(int offset, int count) However, I can't see a way to take advantage of this, even though I'd like to... I'd like to be able to use foreach to iterate over a section of the ArrayList, but can't find any syntax that will work. The obvious: foreach char ch in arList(0,20)
4
5080
by: John C | last post by:
I'm new to C#, so just point me at the correct reference material if this question has been answered before. When creating a new class which implements the IDictionary interface, two versions of the GetEnumerator method must be defined (one from the IDictionary interface, one from the IEnumerable interface). The first is defined as: public IDictionaryEnumerator GetEnumerator()
9
4172
by: Ty Moffett | last post by:
Is there anything obvious wrong with this little loop? The second statement throws an exception "Enumeration has not started. Call MoveNext." I thought that is what I did in line one. My intent here is to take what is left in the queue and write it back to the text file from which it came so it can survive an upcoming reboot.
2
1557
by: Sam Marrocco | last post by:
I've constructed a class that inherits the NameObjectCollectionBase class. All works well, but I'd like to shadow the GetEnumerator method so that it returns an actual value *instead of a DictionaryEntry*. I've gotten strange errors when attempting to override GetEnumerator, such as 'GetEnumerator() cannot override 'Public Overridable NotOverridable Function GetEnumerator() because it is declared NotOverridable......yes, it actually...
2
19859
by: Steve Richter | last post by:
very confused on how to implement the IEnumerable and IEnumerator interfaces on a generic type. I understand I should just use a foreach loop in the GetEnumerator method and use "yield return", etc. would like to know how implement my generic GetEnumerator to yield return an interface to IEnumerator<T>. I am getting a compile error that reminds me a lot of C++ template programming. thanks,
3
3734
by: =?Utf-8?B?cmNoZg==?= | last post by:
I know this is simple problem but I am so new that there is some fundamental disconnect in my understanding of: Enumerable, Enumerator, and Generics. As a result I am having a problem debugging this error message "Error 1 'SimpleSite.Email.Model.Hosts' does not implement interface member 'System.Collections.IEnumerable.GetEnumerator()'. 'SimpleSite.Email.Model.Hosts.GetEnumerator()' is either static, not public, or has the wrong return...
2
1366
by: =?Utf-8?B?VGVk?= | last post by:
I have been asked to change an existing program which Implemented a Collection Class The current class had what is below (its just a summary of the code) Public Class FieldList Implements System.Collections.IEnumerable Private thisColl As Collection
13
5411
by: Tamagafk | last post by:
Hi! Looks like there is a bug in php. If I have function which uses foreach to run trough array recursively, the lop-level foreach interupted by lover-level foreach'es. If I use simply 'for' everything is ok. Example: I have an array of 3 objects connected hierarchically by their variables id and parentId, here is the hierarchy: id=1 parentId=0 ....id=2 parentId=1 ....id=3 parentId=1
2
2173
by: Tony | last post by:
Hello! According to the documentation we have the following interface IList : ICollection, IEnumerable { I can understand all the methods in this IList } interface ICollection : IEnumerable {
0
8370
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8283
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8811
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
8704
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...
1
8470
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8590
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
6160
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
5620
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
1914
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.