473,395 Members | 1,999 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

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

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.
Sep 19 '08 #1
8 1415
On Sep 19, 4:56*am, Family Tree Mike
<FamilyTreeM...@discussions.microsoft.comwrote:
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.
What would be that example, FTM? The example I gave was from MDN and
it in turn was from an earlier example (same author, he just didn't
have the latter part "You can have the best of both worlds.."
RL
Sep 19 '08 #2
Sorry, I cannot think back how to do this in VS 2003.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NameGenerator
{
public class Namer : IEnumerable<string>
{
public string [ ] FirstNames;
public string [ ] LastNames;

IEnumerator<stringIEnumerable<string>.GetEnumerato r ()
{
for (int idxLast = 0; idxLast < LastNames.Count (); ++idxLast)
for (int idxFirst = 0; idxFirst < FirstNames.Count (); ++idxFirst)
yield return string.Format ( "{0} {1}",
FirstNames [idxFirst], LastNames [idxLast] );
}

System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator ()
{
for (int idxLast = 0; idxLast < LastNames.Count (); ++idxLast)
for (int idxFirst = 0; idxFirst < FirstNames.Count (); ++idxFirst)
yield return string.Format ( "{0} {1}",
FirstNames [idxFirst], LastNames [idxLast] );
}
}
class Program
{
static void Main ( string [ ] args )
{
Namer nlist = new Namer ();
nlist.FirstNames = new string [ ] { "Ray", "Casey", "Zanaida" };
nlist.LastNames = new string [ ] { "Anthony", "Gonzales", "Lopez",
"Jones" };

foreach (string s in nlist)
Console.Out.WriteLine ( string.Format ( "The next name is: {0}", s )
);

Console.In.ReadLine ();
}
}
}
Sep 19 '08 #3
On Sep 19, 10:51*am, Family Tree Mike
<FamilyTreeM...@discussions.microsoft.comwrote:
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

////////////

Thanks FTM. I guess your program was to demonstrate the above. I
appreciate it, but I note that essentially you can do the same thing
with a simple call to a function that does a sort and so forth, at the
cost of foregoing the 'foreach' notation.

In any event, I'm not sure your code would work however, since I don't
see any of the three required functions of IEnumerator--MoveNext,
Resent, and Current.

RL

Sep 19 '08 #4
On Sep 19, 1:19*pm, raylopez99 <raylope...@yahoo.comwrote:
On Sep 19, 10:51*am, Family Tree Mike<FamilyTreeM...@discussions.microsoft.comwrote :

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

////////////

Thanks FTM. *I guess your program was to demonstrate the above. *I
appreciate it, but I note that essentially you can do the same thing
with a simple call to a function that does a sort and so forth, at the
cost of foregoing the 'foreach' notation.
Just to make sure I understand what you're saying...you could create a
function that generates a new collection whose elements are the result
of the operation that figures out all possible combinations of the
first and last name right?

The disadvantage of that is that the entire operation has to complete
before the caller can work with that new collection. If you choose to
go down the IEnumerable/IEnumerator route then the caller could exit
out of the foreach enumeration early and *before* the operation (to
figure out the combinations of first and last name) has completed.
>
In any event, I'm not sure your code would work however, since I don't
see any of the three required functions of IEnumerator--MoveNext,
Resent, and Current.
You don't see them because 1) the yield keyword was used to instruct
the compiler to create the IEnumerator automatically and 2) the
foreach keyword was used to instruct the compiler to call those
methods on IEnumerator automatically. Use ILDASM to examine to the
resultant assembly.
Sep 19 '08 #5
On Sep 20, 4:03*pm, "Family Tree Mike"
<FamilyTreeM...@ThisOldHouse.comwrote:
Change the code to look like this in your foreach within main:

foreach (string s in ((IEnumerable <string>)nlist))
* Console.Out.WriteLine(string.Format("The next name is: {0}", s));

foreach (int i in ((IEnumerable<int>)nlist))
* Console.Out.WriteLine(string.Format("The next integer is: {0}", i));

Thanks FTM, that worked.

BTW, a minor aside, I notice that you 'repeat' GetEnumerator() ***
(see below) rather than use the 'convention', that I've seen in some
books, of this format (for the non-generic IEnumerator, which is
required):

IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}

But, when I tried this above 'convention' in your code, I could not
compile it, in fact, IntelliSense would not even recognize
GetEnumerator (!). So I wonder if you've come across this.
However,it's not a big deal since I just use your convention and it
works fine.

Thanks again,

RL

***

System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator()
{
for (int idxLast = 0; idxLast < LastNames.Count(); idxLast
+
+)
//BTW ++idxLast (made globally) also works fine, strangely enough
for (int idxFirst = 0; idxFirst < FirstNames.Count();
idxFirst++)
yield return string.Format("{0} {1}",
FirstNames[idxFirst], lastNames[idxLast]);

for (int i = 0; i < iArrNamer.Length; i++)
{
yield return iArrNamer[i];
}
Sep 21 '08 #6
Yes, I have noted what you said too. I believe it is because the
GetEnumerator()
is not a callable thing. It is used from the foreach context as has been
noted. You
don't really call it from the code. Hopefully one of the other folks can
explain the
details of why the method itself isn't callable. I just found an example
that I follow
and have continued on the tradition, so to speak...

"raylopez99" <ra********@yahoo.comwrote in message
news:fd**********************************@y38g2000 hsy.googlegroups.com...
On Sep 20, 4:03 pm, "Family Tree Mike"
<FamilyTreeM...@ThisOldHouse.comwrote:
Change the code to look like this in your foreach within main:

foreach (string s in ((IEnumerable <string>)nlist))
Console.Out.WriteLine(string.Format("The next name is: {0}", s));

foreach (int i in ((IEnumerable<int>)nlist))
Console.Out.WriteLine(string.Format("The next integer is: {0}", i));

Thanks FTM, that worked.

BTW, a minor aside, I notice that you 'repeat' GetEnumerator() ***
(see below) rather than use the 'convention', that I've seen in some
books, of this format (for the non-generic IEnumerator, which is
required):

IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}

But, when I tried this above 'convention' in your code, I could not
compile it, in fact, IntelliSense would not even recognize
GetEnumerator (!). So I wonder if you've come across this.
However,it's not a big deal since I just use your convention and it
works fine.

Thanks again,

RL

***

System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator()
{
for (int idxLast = 0; idxLast < LastNames.Count(); idxLast
+
+)
//BTW ++idxLast (made globally) also works fine, strangely enough
for (int idxFirst = 0; idxFirst < FirstNames.Count();
idxFirst++)
yield return string.Format("{0} {1}",
FirstNames[idxFirst], lastNames[idxLast]);

for (int i = 0; i < iArrNamer.Length; i++)
{
yield return iArrNamer[i];
}

Sep 21 '08 #7


Brian Gideon wrote:
>
Instead of declaring multple GetEnumerator methods that return
IEnumerator objects why not declare different methods with different
names that return IEnumerable objects. When used in a member that
returns an IEnumerable the yield keyword will cause the compiler to
automatically generate an appropriate IEnumerable and IEnumerator
combination. That's the general pattern I was referring to when I
metioned the Dictionary.Values and Dictionary.Keys properties in
another post.
Like so many things in programming, without a specific example it's a
no-go. Just tried various permuations and it won't work.

If it's simple enough to show please show us.

Otherwise I'll stick to FTM's convention, which works and is not an
eyesore to me.

RL
Sep 22 '08 #8
On Sep 22, 2:48*am, raylopez99 <raylope...@yahoo.comwrote:
Brian Gideon wrote:
Instead of declaring multple GetEnumerator methods that return
IEnumerator objects why not declare different methods with different
names that return IEnumerable objects. *When used in a member that
returns an IEnumerable the yield keyword will cause the compiler to
automatically generate an appropriate IEnumerable and IEnumerator
combination. *That's the general pattern I was referring to when I
metioned the Dictionary.Values and Dictionary.Keys properties in
another post.

Like so many things in programming, without a specific example it's a
no-go. *Just tried various permuations and it won't work.

If it's simple enough to show please show us.

Otherwise I'll stick to FTM's convention, which works and is not an
eyesore to me.

RL
Understood. Here's the shortest possible example I could come up with
to demonstrate everything you want to do. That is...define iterators
that enumerate the constituent variables of a composite class 1)
individually and 2) together. Notice that I use the yield keyword in
the context of members that return IEnumerable instead of
IEnumerator. I think with this example you'll see the power and
elegance behind the IEnumerator/IEnumerable/foreach pattern.

class Program
{
static void Main(string[] args)
{
MyCollection a = new MyCollection();

foreach (string name in a.FirstOnly)
{
Console.WriteLine(name);
}

foreach (string name in a.LastOnly)
{
Console.WriteLine(name);
}

foreach (string name in a.Combination)
{
Console.WriteLine(name);
}
}
}

public class MyCollection
{
private string[] m_First = { "Brian", "Ray" };
private string[] m_Last = { "Gideon", "Lopez" };

public MyCollection()
{
}

public IEnumerable<stringFirstOnly
{
get
{
foreach (string name in m_First)
{
yield return name;
}
}
}

public IEnumerable<stringLastOnly
{
get
{
foreach (string name in m_Last)
{
yield return name;
}
}
}

public IEnumerable<stringCombination
{
get
{
foreach (string first in m_First)
{
foreach (string last in m_Last)
{
yield return first + " " + last;
}
}
}
}
}
Sep 22 '08 #9

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

Similar topics

4
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 :...
0
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...
32
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...
13
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...
104
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...
14
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)...
2
by: pkpatil | last post by:
Hi, Can a private composite object in a class access private or protected members of base class? For e.g. class composite { void memberFunction(); };
10
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...
4
by: Peter Morris | last post by:
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...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...
0
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...
0
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...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.