jeudi 9 avril 2015

Outputting items in a collection in groups


Vote count:

0




I'm currently mulling over whether it is possible to loop through a collection using C# but organise the items in the collection into groups and output them in this way.


So, I have my collection as follows:



<ul class="list-unstyled">
@foreach (IPublishedContent destination in destinations.Descendants("country").OrderBy(x => x.Name))
{
<li><a href="@destination.Url">@destination.Name</a></li>
}
</ul>


This outputs however many items there are in the collection as links. However, what if I wanted to group 6 of these items each into their own unordered list so instead of having just one unordered list I have 4 if there were 24 items in my collection?


I'm using Razor so initially I came up with the following (somewhat broken logic) but this will fail to validate in Razor because of unclosed html tags.



int count = 0;

@foreach (IPublishedContent destination in destinations.Descendants("country").OrderBy(x => x.Name))
{
if (count == 0){ <ul class="list-unstyled">}

<li><a href="@destination.Url">@destination.Name</a></li>

@count++

if(count == 5){
count = 0;
</ul>
}
}


Also, this logic is fundamentally flawed as it requires there to be an exact divisible number of items in the collection. Furthermore, when the collection comes to an end you would be left without a closing tag amongst other issues.


Does anyone have any suggestions as to an alternate approach? I did think that it would be possible to use some lamda functions to achieve this but i'm still fairly new to Linq so not too sure.


Any suggestions would be greatly appreciated.



asked 3 mins ago

jezzipin

1,552






Outputting items in a collection in groups

Aucun commentaire:

Enregistrer un commentaire