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.
What I want to do is something like this:
row 1 | list item 1 | list item 2
row 2 | list item 3 | list item 4
and so on.....
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>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With