使用foreach循环时显示泛型列表每行两个列表项

使用foreach循环时显示泛型列表每行两个列表项

问题描述:

我有一个的传递给视图对象的泛型列表。目前,每个列表项被显示给用户的行逐行

I have a generic list of objects that's passed to a view. Currently, each list item is displayed to the user row-by-row:

@foreach (var result in Model.SearchResults)
{
    result.Address.TownCity
    // ...
}

因此​​,每个列表项显示在自己的行。这个美学不看最好的,因为有留下相当多的空白了。

So each list item is displayed in its own row. Aesthetically this doesn't look the best, as there's quite a lot of white space left over.

我想要做的是这样的:

第1行|列表项1 |列表项2

row 1 | list item 1 | list item 2

行2 |列表项3 |列表项4

row 2 | list item 3 | list item 4

等等.....

这是不是我要做服务器端,即把我的名单的一半到另一个列表,并在视图中有两个foreach循环 - 每一个灌装列,行由行?或者是有反正这可以在视图中使用剃刀做?

Is this something I have to do server-side i.e. put half of my list into another list and in the view have two foreach loops - each one filling a column, row-by-row? Or is there anyway this can be done in the view using razor?

您可以将每个组行通过批处理的每个项目做到这一点归入'批次',然后循环。

You can do this to group each set of rows into 'batches' and then loop through each item in the batch.

@{
    var batches = Model.SearchResult
        .Select((x, i) => new { x, i })
        .GroupBy(p => (p.i / 2), p => p.x);
}
@foreach(var row in batches)
{
    <span>Row @row.Key</span>
    @foreach(var item in row)
    {
        <span>| @item.Address.TownCity</span>
    }
}

另外,您可以使用此;这是简单的,虽然少了几分优雅。

Alternatively you can use this; it's simpler, though a bit less elegant

@{
    var resultArray = Model.SearchResult.ToArray(); // only necessary if SearchResult is not a list or array
}
@for(var i = 0; i < resultArray.Length; i++)
{
    var item = resultArray[i];
    if (i % 2 == 0)
    {
        <span>Row @(i / 2)</span>
    }
    <span>| @item.Address.TownCity</span>
}