We're going to create an array, a list and a dictionary, then loop through each one to retrieve the desired data from each one by using foreach
loops.
LearningScript
as shown in the next screenshot.As we looped through each list, we decided which data to display to the Console:
The analysis of the code is as follows:
For each list we created, we populated them using a Collection Initializer.
string[] ponyArray = new string[] {"AppleJack", "Rarity"};
A string
array named ponyArray
is declared and two strings are added.
foreach(string pony in ponyArray)
A foreach
loop is used to retrieve one element, a pony name string, stored in ponyAr
ray
.
A variable is declared named pony
to hold the retrieved pony name.
Once a pony name is retrieved, the foreach
code block, lines 13 to 16, is executed.
This looping continues until each element in ponyArray
has been retrieved and tested in the code block.
if(pony == "Rarity");
If the retrieved string stored in pony
is equal to "Rarity"
, then line 15 executes.
Debug.Log("I was looking for " + pony);
The string I was looking for plus the string value stored in pony is displayed in the Console.
List<string> ponyList = new List<string>() {"Princess Cadence", "Fluttershy"};
A List
named ponyList
is declared that will store the string
type, and two strings are added.
foreach(string pony in ponyList)
A foreach
loop is used to retrieve one element, a pony name string
, stored in po
ny
List
.
A variable is declared named pony
to hold the retrieved pony name.
Once a pony name is retrieved, the foreach
code block (that is, lines 22 to 25) is executed.
This looping continues until each element in ponyList
has been retrieved and tested in the code block.
if(pony == "Fluttershy")
If the retrieved string stored in pony
is equal to "Fluttershy"
, then line 24 executes.
Debug.Log("I was looking for " + pony);
The string I was looking for plus the string value stored in pony
is displayed in the Console.
Dictionary<int, string> ponyDictionary = new Dictionary<int, string>() {{10, "Nightmare Moon"}, {20, "Rainbow Dash"}};
A Dictionary
named ponyDictionary
is declared with key and value of type <int, string>
, and two key/value pairs are added.
foreach(KeyValuePair<int, string> pony in ponyDictionary)
A foreach
loop is used to retrieve one KeyValuePair
, a key and value, stored in ponyDictionary
.
A variable is declared named pony
to hold the retrieved KeyValuePair
.
Once a key value and a pony name string are retrieved, the foreach
code block (that is, lines 31 to 34) is executed.
This looping continues until each KeyValuePair
in ponyDictionary
has been retrieved and tested in the code block.
if(pony.Key == 20)
If the retrieved Key
stored in pony is equal to 20
, then line 33 executes.
Debug.Log("I was looking for " + pony.Value);
The string I was looking for
plus the string value stored in pony.Key
is displayed in the Console.
18.119.253.31