[英]Looping through multi dimensional array
這里采取的方法是完全錯誤的。 這是應該如何完成的。
public class Recipe {
public List<string> ingredients;
public string result;
public Recipe (List<string> _ingredients, string _result) {
this.ingredients _ingredients;
this.result = _result;
}
}
然后在循環時:
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")
}
這也意味着循環會簡單得多。
我有一個包含以下數組的 C# 腳本:
string[,] craftingRecipes = new string[,]{
// {recipe},{result}
{"potato","tabasco"},{"explosivePotato"},
{"mentos","cola"},{"colaCannon"},
{"potato","cola"},{"potatoCola"},
{"potato","chips"},{"potatoChips"}
};
如何遍歷第 n 個子數組中的每個項目? 因此,例如包含{"potato","tabasco"}
的數組應該循環兩次,因為其中有兩個項目。
感謝您的任何幫助!
我不確定我是否理解您的問題,因為您的代碼無法編譯,但是您可以使用此循環來遍歷第一“行”中的項目:
int line = 0;
for (int i = 0; i < craftingRecipes.GetLength(1); i++)
{
Console.WriteLine(craftingRecipes[line,i]);
}
雖然,您的array
應該看起來更像這樣(我必須添加sth_missing_here
,因為Multi-Dimensional Array
必須具有相同長度的子數組):
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"}
};
您可以使用OfType<T>
方法將多維數組轉換為IEnumerable<T>
結果,例如:
IEnumerable<string> items = craftingRecipes.OfType<int>();
foreach(var item in items)
{
// loop between all elements...
}
根據 19-09-2018 的編輯,現在可以正確回答這個問題。
使用兩個簡單的嵌套foreach
循環foreach
數組。
foreach (Recipe recipe in recipes) {
System.Console.Write("To make '{0}' you need:", recipe.result);
foreach (ingredient in recipe.ingredients) {
System.Console.Write(ingredient);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.