我正在尝试在两列表中显示foreach迭代的结果。 这是我的代码:
<table>
@foreach (var item in items)
{
<tr>
<td>
@item.value
</td>
</tr>
}
</table>
输出:
value1
value2
value3
value4
value5
问:我如何实现:
value1 value2
value3 value4
value5
答案 0 :(得分: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
并考虑项目类型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>
答案 1 :(得分: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>