When to use each type of cycle?

I learn the basics of programming here (C #), but I think this question is general.

What are some simple practical situations that come closer to a particular type of cycle?

The while and for loops seem pretty similar, and there are a few SO questions about the differences between them. How about foreach ? In my basic understanding, it seems that I should do everything that the foreach executes in the for loop.

+4
source share
7 answers

1. foreach and for

A foreach works with IEnumerator when a for loop works with an index (in object myObject = myListOfObjects[i] , I am an index).

There is a big difference between the two:

  • an index can directly access any object based on its position in the list.

  • the enumerator can access only the first element of the list, and then move on to the next element (as described in the previous link from msdn). It cannot access the element directly, just knowing the index of the element in the list.

Thus, the counter may seem less powerful, but:

  • You do not always know the position of elements in a group, because all groups are not ordered / indexed.
  • You don’t always know the number of items in a list (think of a linked list).
  • even if it was ordered, indexed access to the list can be based internally on an enumerator, which means that every time you access an element by its position, you can actually list all the elements of the list as long as the element you want.
  • indices are not always numeric. Think of a Dictionary .

Thus, the great power of the foreach and the basic use of IEnumerator is that it applies to any type that implements IEnumerable (implementing IEnumerable simply means that you provide a method that returns an enumerator). Lists, arrays, dictionaries, and all other types of groups implement IEnumerable. And you can be sure that the counter they have is as good as it gets: you won’t find a quick way to view the list.

So, a for loop can usually be thought of as a specialized foreach :

 public void GoThrough(List<object> myList) { for (int i=0; i<myList.Count; i++) { MessageBox.Show(myList[i].ToString()); } } 

perfectly equivalent to:

 public void GoThrough(List<object> myList) { foreach (object item in myList) { MessageBox.Show(item.ToString()); } } 

I said at all, because there is an obvious case when a for loop is needed: when you need an index (i.e. a position in a list) of an object, for some reason (for example, displaying it). You will, in the end, realize that this only happens in certain cases when you are good at programming .NET, and that foreach should be your default candidate for loops over a group of elements.

Now, to continue comparing the foreach , this is really just an eye-specific loop in the loop:

 public void GoThrough(IEnumerable myEnumerable) { foreach (object obj in myEnumerable) { MessageBox.Show(obj.ToString()); } } 

perfectly equivalent to:

 public void GoThrough(IEnumerable myEnumerable) { IEnumerator myEnumerator = myEnumerable.GetEnumerator(); while (myEnumerator.MoveNext()) { MessageBox.Show(myEnumerator.Current.ToString()); } } 

The first letter is much simpler, but.

2. while and do..while

The while (condition) {action} cycle and the do {action} while (condition) cycle simply differ from each other in that the first checks the condition before applying the action, when the second applies the action, then checks the condition. The do {..} while (..) used rather insignificantly compared to others, because it starts the action at least once, even if the condition is not initially met (which can lead to problems, since the action usually depends on terms).

The while more general than the for and foreach tags, which are specific to object lists. The while has only a condition that can be based on anything. For instance:

 string name = string.empty; while (name == string.empty) { Console.WriteLine("Enter your name"); name = Console.ReadLine(); } 

asks the user to enter their name and press Enter until they enter anything. As you can see, nothing to do with lists.

3. Conclusion

When you are browsing the list, you should use foreach if you don't need a numerical index, in which case you should use for . When this has nothing to do with the list, and it's just a procedural construct, you should use while(..) {..} .

Now, in conclusion, with something less restrictive: your first goal with .NET should be to make your code readable / supported and make it work quickly, in that order of priority. Everything that accomplishes this is good for you. Personally, I think the foreach has the advantage of being potentially the most readable and fastest.

Edit: there is another case where the for loop is useful: when you need indexing to go through the list in a special way or if you need to change the list when in a loop. For example, in this case, since we want to remove every empty element from myList:

 for (int i=myList.Count-1; i>=0; i--) { if (myList[i] == null) myList.RemoveAt(i); } 

Here we need a for loop because myList cannot be changed from a foreach , and we need to go back because if you delete an element at position i, the position of all elements with index> i will change.

But the use of these special designs has been reduced since LINQ. The last example can be written as follows in LINQ, for example:

 myList.RemoveAll(obj => obj == null); 

LINQ is the second step, although learn the loops first.

+5
source

Which is best for reading code. In other words, use the one that best suits the situation.

while : When you have a condition that needs to be checked at the beginning of each cycle. for example while(!file.EndOfFile) { }

for : When you have an index or counter, you increment each loop. for (int i = 0; i<array.Length; i++) { } . Essentially, what you are looping is an indexed collection, array, list, etc.

foreach : When you iterate over a collection of objects or other Enumerable. In this case, you may not know (or not care) the size of the collection, or the collection is not based on an index (for example, a collection of objects). I usually find that foreach loops are the most readable when I'm not interested in the index of anything or any other exit conditions.

These are my general general rules.

+9
source

when you know how many iterations will be used for

when you don’t know, use while , when you don’t know and must execute the code at least once, use do

when you iterate over a collection and don’t need to use the foreach index (also you cannot use collection[i] for everything you can use foreach on)

+2
source

As others have said, "it depends."

I find that I use simple "for" loops very rarely these days. If you start using Linq, you will find that you don’t need loops at all, and when you do this so-called foreach loop that called.

Ultimately, I agree with Colin Mackay - code for readability!

+1
source

The do while been forgotten, I think :)

Taken from here .

The C # while statement executes a statement or statement block until the specified expression evaluates to false. In some situations, you can loop at least once, and then check the condition. In this case, you can use the do..while .

The difference between do..while and while is that do..while evaluates its expression at the bottom of the loop instead of the top. Therefore, instructions inside the do block are always executed at least once. From the example below, you can understand how the while function works. While.

 using System; using System.Windows.Forms; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { int count = 5; do{ MessageBox.Show(" Loop Executed "); count++; }while (count <=4); } private void button2_Click(object sender, EventArgs e) { int count = 5; while (count <=4){ MessageBox.Show(" Loop Executed "); count++; } } } } 
+1
source

If you have a collection and you plan to use all the values ​​in advance, use foreach , since it is usually easier to work with the “current” instance.

If any condition can cause you to stop the iteration, you can use for or , as well . They are very similar, the big difference is that for gets control over updating the current index or value (in the ad for the ad), because after a while you decide when and where in for now to update some values, which are then checked in the predicate while.

0
source

If you are writing a parser class, say XMLParser, that will read XML nodes from a given source, you can use a while loop, since you do not know how many tags there are. You can also use it when you iterate if the variable is true or not.

You can use for a loop if you want to control your iterations a bit

0
source

Source: https://habr.com/ru/post/1332776/


All Articles