Click here to Skip to main content
14,695,590 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Two of my Text/Reference books say that it is better to use For Each...Next loops if possible as opposed to For...Next loops. I am using the code shown below. It works fine. What the code does is move partial rows of data (columns 1 through 4 and column 6) from one dgv1 control to another dgv2 control, where column 1 must meet the If criteria. My question is, how would this code look if it used a For Each construct.

For Me.g = 0 To dgv1.RowCount - 1
            If dgv1(0, g).Value = txtClass.Text Then
                dgv2.Rows.Add()
                For Me.h = 1 To 4
                    dgv2(h, j).Value = dgv1(h, g).Value
                Next
                dgv2(6, j).Value = dgv1(6, g).Value
                j = j + 1
            End If
        Next
Posted

Please, read this article:
FOREACH Vs. FOR (C#)[^]
In .NET, which loop runs faster, 'for' or 'foreach'?[^]

Member 10628309 asked:
how would this code look if it used a For Each construct.

For Me.g = 0 To dgv1.RowCount - 1
            If dgv1(0, g).Value = txtClass.Text Then
                dgv2.Rows.Add()
                For Me.h = 1 To 4
                    dgv2(h, j).Value = dgv1(h, g).Value
                Next
                dgv2(6, j).Value = dgv1(6, g).Value
                j = j + 1
            End If
        Next


for example:
For Each r As DataGridViewRow In DataGridViewRowCollection
    'for loop body
Next 


For further information, please see:
For Each... Next statement[^]
DataGridViewRow[^]
DataGridViewCollection[^]
   
v2
Comments
   
5ed. Actually, I later saw that my answer did not address the problem apparent from the inquirer's code sample. I only responded to the title of the question. (My bad, sometimes I don't use my huge patience. It's really huge, only I don't use it in all cases. :-) I just thought about fixing my answer to address this particular problem, but you already answered, thank you.
—SA
Maciej Los 3-Jun-15 15:27pm
   
Thank you, Sergey.
This is simple enough. If in each iteration you need index of the element, use "for". If you need to guarantee certain order of operations, use "for". In all other cases, try to use "foreach".

One delicate case is when you need to modify the set you are iterating during iterations, in particular, remove some elements, one approach is: using "for" iterating from high index to low index. Be very careful with such cases. Other, more complicated cases, need special consideration. In such cases, just use you logic.

Remember that exact behavior of "foreach" depends on how the interface System.IEnumerable is implemented, how its implementation of System.Collections.IEnumerator behaves. Please see:
https://msdn.microsoft.com/en-us/library/system.collections.ienumerable%28v=vs.110%29.aspx[^],
https://msdn.microsoft.com/en-us/library/system.collections.ienumerable.getenumerator(v=vs.110).aspx[^],
https://msdn.microsoft.com/en-us/library/system.collections.ienumerator%28v=vs.110%29.aspx[^].

For one thing, it would be wise not to rely on any peculiar features known from a particular implementation of this interface. From the other hand, you can implement this interface in a specific way, to make some extra assumptions valid, but I would not recommend it.

If you want to say: "this answer pretty much says 'it depends', nothing else", this is essentially what it meant to be. :-)

[EDIT]

I later realized that my answer did not address some more specific problems of the question. So, please see Solution 2 and my comment to it.

—SA
   
v2
Comments
Maciej Los 3-Jun-15 14:50pm
   
Why someone downvoted it?
This is good answer. +5!
   
Thank you, Maciej.

Ha-ha, it looks like some people are fighting over my answers in some weird ways these days. (And this is a hi-rep case.) What would you say, for example, about this funny thing: http://www.codeproject.com/Answers/997285/MS-Web-Development-Which-to-learn-in?? :-)

That would be all right, but it also hurts my favorite "JavaScript Calculator" article. I really think this is one of the most useful, because I tried to dismiss serious misconceptions and because this is my real working tool which could be useful for many. One user even sent me his gratitude on my personal contact.

—SA
   
Frankly, the person who down-voted this answer could have some valid reasons.
This person could keep in mind some important consideration which should be taken into account; which I missed or even failed to see. Some may see important performance difference, which I did not even consider.

Only this is one of the cases when a comment would be helpful. (No, I don't say all down-voted on answers should be commented; some don't even deserve a comment, but I hope many my answers do deserve commenting. :-)

—SA
Maciej Los 3-Jun-15 15:12pm
   
Some people misunderstood the way we can help. One of them is to "giving a fish" and the second one is to "giving a fishing rod". Both are acceptable, but everyone knows that the second way is much, much better!
   
Set aside teaching how to fish. Apparently some take the attempt to teach them as an offense. Those may not even accept a fish, they will wait until someone fry it and serve on a plate, where they won't eat it anyway... :-(
—SA
Maciej Los 3-Jun-15 15:30pm
   
Keeping in mind the past does not help in judging...
Maciej Los 3-Jun-15 15:37pm
   
What kind of fish do you serve today? :laugh:
I really do like herring with jigger of vodka... Cheers, Sergey! Na zdrowie!
   
I have a very interesting post to write on this proverb. I hope you will like it. When I'm done I'll notify you.

Interestingly, In US there is no much herring. Some know this word and fish, some never heard of it. Most of it comes from Russian/Ukrainian/Jewish businesses. But the supply of fish elsewhere and the variety greatly improved during last ears, I guess, mostly due to increasing farming. When I moved here, I was just shocked by extremely scarce choice and high prices. Not a problem right now.

Будем здоровы!

—SA
Maciej Los 3-Jun-15 16:03pm
   
Let's move our discussion to Skype... ;)
   
I don't mind but you are hard to reach. I would enjoy having a conversation.
—SA
Maciej Los 3-Jun-15 17:56pm
   
I was, let's say: outside ;)
Did you receive my message?
   
No; sorry, I'll be able to get to it (if you mean Skype) much later tonight. In worst case, we might be able to contact on weekend, but I'm online every late evening/night and usually in the morning.
—SA
Maciej Los 3-Jun-15 18:04pm
   
OK, let's try to be in touch on weekend...
   
Now, this is my post on teaching fishing I promised to show:
Feeding Apple or Why Don't We Answer Some Questions.

I hope you like my own saying mocking this old proverb. :-)

—SA
I think your code is well addressed by the For .. Next loop.
However, I wouldn't have used member variables as loop indices even if my life depended on it.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900