473,804 Members | 2,133 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1436
On Sep 19, 4:56*am, Family Tree Mike
<FamilyTreeM... @discussions.mi crosoft.comwrot e:
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.Collecti ons.Generic;
using System.Linq;
using System.Text;

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

IEnumerator<str ingIEnumerable< string>.GetEnum erator ()
{
for (int idxLast = 0; idxLast < LastNames.Count (); ++idxLast)
for (int idxFirst = 0; idxFirst < FirstNames.Coun t (); ++idxFirst)
yield return string.Format ( "{0} {1}",
FirstNames [idxFirst], LastNames [idxLast] );
}

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

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

Console.In.Read Line ();
}
}
}
Sep 19 '08 #3
On Sep 19, 10:51*am, Family Tree Mike
<FamilyTreeM... @discussions.mi crosoft.comwrot e:
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...@yah oo.comwrote:
On Sep 19, 10:51*am, Family Tree Mike<FamilyTree M...@discussion s.microsoft.com wrote:

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.c omwrote:
Change the code to look like this in your foreach within main:

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

foreach (int i in ((IEnumerable<i nt>)nlist))
* Console.Out.Wri teLine(string.F ormat("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.Get Enumerator()
{
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.Collecti ons.IEnumerator
System.Collecti ons.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.Coun t();
idxFirst++)
yield return string.Format(" {0} {1}",
FirstNames[idxFirst], lastNames[idxLast]);

for (int i = 0; i < iArrNamer.Lengt h; 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********@yah oo.comwrote in message
news:fd******** *************** ***********@y38 g2000hsy.google groups.com...
On Sep 20, 4:03 pm, "Family Tree Mike"
<FamilyTreeM... @ThisOldHouse.c omwrote:
Change the code to look like this in your foreach within main:

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

foreach (int i in ((IEnumerable<i nt>)nlist))
Console.Out.Wri teLine(string.F ormat("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.Get Enumerator()
{
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.Collecti ons.IEnumerator
System.Collecti ons.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.Coun t();
idxFirst++)
yield return string.Format(" {0} {1}",
FirstNames[idxFirst], lastNames[idxLast]);

for (int i = 0; i < iArrNamer.Lengt h; 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.Valu es 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...@yah oo.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.Valu es 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.WriteLi ne(name);
}

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

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

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

public MyCollection()
{
}

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

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

public IEnumerable<str ingCombination
{
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
1442
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
4160
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
2004
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
7207
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
1812
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.
2
2657
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
2965
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
4
2568
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 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<MyTreeNode> {
0
9595
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
10603
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...
1
10356
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
10099
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...
0
9176
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6869
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();...
0
5536
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
5675
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3836
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.