Now, in previous articles we talked about Loop. We’ve seen the for loop, the While loop, and the Do While loop.
But if you remember, there is another Loop: FOREACH LOOP.
Now, i’m talk about this only now because this is Loop is incredible when we use with Collections.
We have seen how declare an Array, and how access to ONE particular element inside the Array.
But if we need to find a data inside the Array? Or a List?
How we can check inside a Collection if we have a specific data?
We have an Array of numbers.
How can check inside ALL THE COLLECTION if we have number 6?
This is our Array.
Now, we know there is a 6 inside.
But create a logic to check if the number 6 is inside the Array is another story.
And here it comes the Foreach Loop.
This Loop is AMAZING with the Collections because it CHECK ANY ELEMENTS IN OUR ARRAY in one run.
I make it more simple : we want print out any element of this Array.
How is the syntax of Foreach Loop?
First, we use keyword “foreach”
If we want we can autocomplete the syntax with TAB as always
We analyze the syntax :
foreach is the keyword of Loop
Inside brackets we pass the condition (var item in collection)
var is the syntax for generic type, we seen before,
item is simple name OF VARIABLE.
To make things more understandable, we can change “item” to what we have inside our collection.
What We search? The numbers right?
it means we try to find number, where? In our Array.
So we have to pass the NAME OF OUR COLLECTION
If we look now at number variable, it becomes an INT TYPE.
Because “number” represent what is inside the Array.
And what is? Int value!
If we READ the code, letteraly, this means
Foreach number we have inside our collection numbers
foreach (var number in numbers)
and inside curly brackets we need to run some code.
Print everything? No problem?
What we need to print? the number inside the Array.
So we pass the variable “number”
If we press Play
We print everything inside our Array!
LITTLE TIP : as always, watch out at one thing.
It is not a problem, but remember :
EVERYTHING WE WRITE IN THE INSPECTOR, OVERRIDE THE CODE
Here we have this
But if in the Inspector I chenage to this
And I press Play
We print out ONLY the 3.
Another tip is this :
If we want to come back and make Inspector EQUAL TO THE CODE, simply RIGHT CLICK OVER THE SCRIPT, then RESET.
To finish, let’s back to our first example.
How search for only one data inside a Collection?
For example, if we have 7 inside, print only that.
Really easy, we need an If Statement, and give the condition
if the number we search for is equal to 7, print it out
And we have our number 7 print out in the Console!
This is the C# Microsoft documentation for Arrays
The next article is about List!!