2015-06-22 142 views
-3

的阵列我有以下数组一个C#脚本:循环通过阵列

string[,] craftingRecipes = new string[,]{ 
    // {recipe},{result} 
    {"potato","tabasco"},{"explosivePotato"}, 
    {"mentos","cola"},{"colaCannon"}, 
    {"potato","cola"},{"potatoCola"}, 
    {"potato","chips"},{"potatoChips"} 
}; 

我怎么能遍历的第n子阵列的每个项目?因此,例如,包含{"potato","tabasco"}的数组应该循环两次,因为其中有两个项目。
谢谢你的帮助!

+1

您的样品不能编译,所以很难看到什么“的第n个子阵”应该是......请出示样品,编译或更好,但考虑使用强类型对象的列表(像'配方{清单组件;字符串结果;}')。 –

回答

1

我不知道我理解你的问题,因为你的代码不能编译,但是你可以用这个循环通过第一个“行”项目迭代:

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

可以使用OfType<T>方法,对多维数组转换为IEnumerable<T>结果,样品:

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

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