循环通过多维数组

时间:2015-06-22 00:30:24

标签: c# arrays

修改

这里采取的方法是完全错误的。这就是它应该如何完成的。

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"}的数组应循环两次,因为其中有两个项目 谢谢你的帮助!

3 个答案:

答案 0 :(得分:2)

我不确定我理解你的问题,因为你的代码没有编译,但是你可以使用这个循环来迭代第一行中的项目:

        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"}
        };

答案 1 :(得分:0)

您可以使用OfType<T>方法将多维数组转换为IEnumerable<T>结果,以获取示例:

IEnumerable<string> items = craftingRecipes.OfType<int>();

foreach(var item in items)
{
   // loop between all elements...
}

答案 2 :(得分:0)

  

根据2018年9月19日的修改,现在可以正确回答此问题。

使用两个简单的嵌套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);
  }
}