简体   繁体   English

如何循环遍历多个数组?

[英]How can I loop through multiple arrays?

I have 2 arrays, one filled with questions, the other with answers pertaining to an FAQ page for my current project. 我有2个数组,一个填充问题,另一个有关于我当前项目的FAQ页面的答案。

I apologize if this seems like a simple problem, but I'm unsure as to how I'd be able to loop through these arrays, generate the HTML to contain them, and then dynamically insert the questions AND the answers. 如果这似乎是一个简单的问题,我很抱歉,但我不确定如何能够遍历这些数组,生成包含它们的HTML,然后动态插入问题和答案。

The questions on their own are pretty simple, as per the below code 根据下面的代码,问题本身很简单

@{
   var Questions = ViewData["Questions"];
   var Answers = ViewData["Answers"];
 }
 @foreach (var question in (string[])ViewData["Questions"])
 {
    var html = string.Format(@"
       <div class='panel-group' id='accordion{1}'>
         <div class='panel panel-default'>
           <div class='panel-heading'>
              <h4 class='panel-title'>
                 <a class='accordion-toggle collapsed' data-toggle='collapse' data-parent='#accordion{1}' href='#collapse{1}'>{0}</a>
              </h4>
          </div>
          <div id='collapse{1}' class='panel-collapse collapse '>
             <div class='panel-body'>answer</div>
          </div>
      </div>", question, IDGenerator);
      @Html.Raw(html);
     IDGenerator.Append("1");

   }

I have attempted a nested foreach statement to do this, but this generates 6 values and I'm unsure how to insert the values from Viewdata["Answers"] into the string, alongside the existing Question without duplication. 我已尝试使用嵌套的foreach语句来执行此操作,但这会生成6个值,并且我不确定如何将Viewdata["Answers"]的值插入到字符串中,与现有问题一起插入而不重复。

Could I perhaps have some insight into this? 我可能对此有所了解吗? any and all help is greatly appreciated. 任何和所有的帮助非常感谢。

The perfect scenario would be create an ViewModel with all information you need (question/anwsers) and return a list of viewModels as model to your view. 完美的场景是创建一个ViewModel其中包含您需要的所有信息(问题/答案),并将viewModel列表作为模型返回给您的视图。 Anyway, give you have the same size for both arrays, you could use an for statement and access each element by index . 无论如何,为两个数组提供相同的大小,您可以使用for语句并按index访问每个元素。 For sample: 样品:

@{
   var questions = (string[]) ViewData["Questions"];
   var answers = (string[]) ViewData["Answers"];
}

@if (questions.Length == answers.Length)
{
   for (int i = 0; i < questions.Lenght; i++)
   {
       // here you can access questions[i] and anwsers[i]
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM