Jonathan Parker

Has anyone ever needed something like this:

int c = 0;

Debug.Assert(collection1.Length == collection2.Length);

foreach(int a in collection1 and int b in collection2)

{

c += a * b;

}

And had to do this:


int c = 0;

for (int i = 0; i < array1.Length; i++)

{

c += array1[i] * array2[i];

}


I think that being able to iterate over two collections simultaneously would be very useful.

What do you think



Re: Visual C# Language Limitations of foreach

Peter Ritchie

What should happen if both collections don't have the same number of elements Should an exception occur




Re: Visual C# Language Limitations of foreach

ruijoel

Maybe just iterate until one of the collections has no items

Code Snippet

int[] coll1 = { 1 , 2 , 3 , 4 };

string[] coll2 = { "first: " , "second: " };

foreach ( int i in coll1 and string s in coll 2 ) {

Console.WriteLine ( s + i.ToString() );

}

would give :

first: 1

second: 2

and no errors or exceptions






Re: Visual C# Language Limitations of foreach

Pin Bender

In python, there's a zip() function for handling this situation. (It creates a new list containing pairs of values from each of the lists.) Perhaps you could introduce something similar in your codebase for accomplishing the same thing. (You could even implement it as an iterator so it doesn't actually need to create a new list.)



Re: Visual C# Language Limitations of foreach

bklare

The code in the "harder" portion is actually looks slighly longer than the code in the "more convenient" portion.

While the foreach loop has its minor conveniences, it is by no means necessary - which leads me to conclude that the hybrid foreach loop you propose is even less necesarry.

For loops are not even necessary because all they are is an interfaced while loop.





Re: Visual C# Language Limitations of foreach

JonathanParker

This isn't about doing something that can't be done any other way. It's about simplifying things and making your code more readable and elegant.





Re: Visual C# Language Limitations of foreach

David J Oldfield

Also noteworthy is the number of ambiguis meanings contained.

foreach(

foreach(

suggests that each entry from item 1 instantiates an entire loop from item 2. I suppose:

foreach( obtype elem in collection, subobtype elem2 in elem.subs )

might serve that purpose, however 9/10 of the time, I am interested in processing obtype elem also... which forces me to write additional handler code to prevent that code from being executed once per child. Seems to me that the very construct is counter-productive.

As far as the ambiguis meanings:

foreach x in y where there is an a in b

foreach x in y

foreach a in b

foreach x in y

{}

foreach a in b

{}

etc.

Yes, it would have exactly one meaning when implimented, but I think that modern codeing is getting ambiguis enough.