2014-08-31 123 views
1

我试图在两列表中显示来自foreach迭代的结果。 这是我的代码:从foreach元素创建一个2列表

<table> 
    @foreach (var item in items) 
    { 
     <tr> 
      <td> 
       @item.value 
      </td> 
     </tr> 
    }     
</table> 

此输出:

value1 
value2 
value3 
value4 
value5 

问:我怎样才能做到:

value1 value2 
value3 value4 
value5 

回答

1
<table> 
    @int amountOfItems = items.Count; 
    for(int index = 0; index < amountOfItems; i++) 
    { 
     if(index % 2 == 0) 
     { 
     <tr> 
      <td> 
       @items[index].value 
      </td> 
     } 
     else 
     { 
      <td> 
       @items[index].value 
      </td> 
     </tr> 
     } 
    } 
    @if(amountOfItems % 2 != 0) 
    { 
     </tr> 
    }     
</table> 

编辑:使用foreach和缺点idering项目是ICollection型或ICollection<T>

<table> 
    @int amountOfItems = items.Count; 
    foreach(var item in items) 
    { 
     int index = items.IndexOf(item); 
     if(index % 2 == 0) 
     { 
     <tr> 
      <td> 
       @items[index].value 
      </td> 
     } 
     else 
     { 
      <td> 
       @items[index].value 
      </td> 
     </tr> 
     } 
    } 
    @if(amountOfItems % 2 != 0) 
    { 
     </tr> 
    }     
</table> 
+0

这可以只使用一个foreach做什么? – alex 2014-08-31 17:37:53

+0

@ alex87我已经更新了答案,只包含'foreach' – Michael 2014-09-01 21:07:21

1

H个的...

<table> 
    @{ 
     var count = mylist.Count; 
     for (int i = 0; i < count; i++) 
     { 
      <tr>      
       <td>@mylist[i]</td> 

       @*or (i & 1) == 0*@ 
       <td>@((i % 2) == 0 ? i + 1 < count ? mylist[++i] : string.Empty : string.Empty)</td> 
      </tr> 
     } 
    } 
</table> 
相关问题