简体   繁体   中英

How to convert a list to nested list in C#

I have a List object

List<string> intList = new List<string>();

I have a,b,c,d,e,f in "intList" object. Normally, HTML render is

<ul>
  <li>a<li>
  <li>b<li>
  <li>c<li>
  <li>d<li> 
  <li>e<li>
  <li>f<li>
</ul>

Above one: I can easily render HTML in MVC view page:

<ul>
   @foreach(var item in Model)
   {
      <li>@item</li>
   }
</ul>

The following a carousel HTML one is difficult render like above code. Any suggestions?

<div id="carousel">
  <div class="item">
    <ul>
      <li>a<li>
      <li>b<li>
    </ul>
  </div>

  <div class="item">
    <ul>
      <li>c<li>
      <li>d<li>
    </ul>
  </div>

  <div class="item">
    <ul>
      <li>e<li>
      <li>f<li>
    </ul>
  </div>
</div>

Do something like:

<div class="item>
    <ul>
       @foreach(var item in Model)
       {
          if(item % 2 == 0)
          {
              </ul>
              </div>
              <div class="item>
              <ul>  
          }
          <li>@item</li>
       }
    </ul>
</div>

You can use a standard for loop and check if the loop variable is > 0 and if it is divisible by 2:

@if (Model.Count > 0)
{
<div class="item">
    <ul>
       @for(int i =0; i<Model.Count; i++)
       {
          if(i> 0 && i % 2 == 0)
          {
              @:</ul>
              @:</div>
              @:<div class="item">
              @:<ul>  
          }
          <li>@Model[i]</li>
       }
    </ul>
</div>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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