The approach taken here was completely wrong. This is how it should have been done.
public class Recipe {
public List<string> ingredients;
public string result;
public Recipe (List<string> _ingredients, string _result) {
this.ingredients _ingredients;
this.result = _result;
}
}
And then when looping:
Recipe[] recipes = new Recipe[] {
new Recipe(new List<string>(new string[] { "potato", "tabasco" }), "explosivePotato"),
new Recipe(new List<string>(new string[] { "mentos", "cola" }), "colaCannon"),
new Recipe(new List<string>(new string[] { "potato", "cola" }), "potatoCola"),
new Recipe(new List<string>(new string[] { "potato", "chips" }), "potatoChips")
}
This would also mean that looping would be a whole lot simpler.
I have a C# script with the following array:
string[,] craftingRecipes = new string[,]{
// {recipe},{result}
{"potato","tabasco"},{"explosivePotato"},
{"mentos","cola"},{"colaCannon"},
{"potato","cola"},{"potatoCola"},
{"potato","chips"},{"potatoChips"}
};
How can i loop through every item in the n'th subarray? So for example the array containing {"potato","tabasco"}
should be looped twice, since there are two items in it.
Thank you for any help!
I'm not sure I understood your question, since your code doesn't compile, but you can use this loop to iterate through items in first "line":
int line = 0;
for (int i = 0; i < craftingRecipes.GetLength(1); i++)
{
Console.WriteLine(craftingRecipes[line,i]);
}
Although, Your array
should look more like this (I had to add sth_missing_here
, because Multi-Dimensional Array
must have sub-arrays with the same length):
string[,] craftingRecipes = new string[,]{
{"potato","tabasco"},{"explosivePotato","sth_missing_here_1"},
{"mentos","cola"},{"colaCannon","sth_missing_here_2"},
{"potato","cola"},{"potatoCola","sth_missing_here_3"},
{"potato","chips"},{"potatoChips","sth_missing_here_3"}
};
You can use the OfType<T>
method, to convert the multidimensional array into an IEnumerable<T>
result, for sample:
IEnumerable<string> items = craftingRecipes.OfType<int>();
foreach(var item in items)
{
// loop between all elements...
}
As per the edit 19-09-2018, this can now be properly answered.
Iterate over the array using two simple nested foreach
loops.
foreach (Recipe recipe in recipes) {
System.Console.Write("To make '{0}' you need:", recipe.result);
foreach (ingredient in recipe.ingredients) {
System.Console.Write(ingredient);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.