C# 通过多维数组循环 编辑
这里采取的方法是完全错误的。这是应该做的C# 通过多维数组循环 编辑,c#,arrays,C#,Arrays,这里采取的方法是完全错误的。这是应该做的 公共类配方{ 公开成分清单; 公共字符串结果; 公共配方(列出配料、串、结果){ 这是成分(配料),; this.result=\u result; } } 然后循环时: Recipe[] recipes = new Recipe[] { new Recipe(new List<string>(new string[] { "potato", "tabasco" }), "explosi
公共类配方{
公开成分清单;
公共字符串结果;
公共配方(列出配料、串、结果){
这是成分(配料),;
this.result=\u 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")
}
如何循环第n个子数组中的每个项?因此,例如,包含{“potato”,“tabasco”}
的数组应该循环两次,因为其中有两个项。谢谢你的帮助 我不确定我是否理解了您的问题,因为您的代码没有编译,但您可以使用此循环迭代第一行中的项:
您可以使用
of type
方法将多维数组转换为IEnumerable
结果,例如:
IEnumerable<string> items = craftingRecipes.OfType<int>();
foreach(var item in items)
{
// loop between all elements...
}
IEnumerable items=craftingRecipes.OfType();
foreach(项目中的var项目)
{
//在所有元素之间循环。。。
}
根据2018年9月19日的编辑,现在可以正确回答这一问题
使用两个简单的嵌套foreach
循环迭代数组
foreach(配方中的配方){
Write(“要生成所需的“{0}”,recipe.result);
foreach(配方中的成分。成分){
系统。控制台。写入(成分);
}
}
您的示例未编译,因此很难看到“第n个子数组”应该是什么。。。请显示编译或更好地考虑使用强类型对象列表的示例(如<代码>配方{列表组件;字符串结果;})。
int line = 0;
for (int i = 0; i < craftingRecipes.GetLength(1); i++)
{
Console.WriteLine(craftingRecipes[line,i]);
}
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"}
};
IEnumerable<string> items = craftingRecipes.OfType<int>();
foreach(var item in items)
{
// loop between all elements...
}