Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate a list for first half no of items

I am trying to iterate a list for only first half of the items, and then again i want to iterate a list for only the remaining other half of the list. Any Ideas ?

@foreach (var category in Model.Categories.OrderBy(i => i.CategoryName))
{
  <li>
    <div id="category_@(category.SKU)" 
         class="itemBlock" 
         onclick="toggle('@(category.SKU)')">
  </li>
}
like image 355
Nanu Avatar asked Sep 01 '25 03:09

Nanu


2 Answers

Something like:

var categories = Model.Categories.OrderBy(i => i.CategoryName).ToList();
int noOfCategories = categories.Count();
int half = noOfCategories/2;

for (int x = 0; x < half; x++)
{
    var category = categories[x];
    //your logic here
}
for (int x = half; x < noOfCategories; x++)
{
    var category = categories[x];
    //your logic here
}

Should do the trick, can't guarantee that the syntax is 100%, but that should give you all you need to do it!

like image 61
Tim Avatar answered Sep 02 '25 17:09

Tim


Just use a for loop.

for(int i=0; i < Model.Categories.OrderBy(i => i.CategoryName).Count/2; i++)
{
    // do stuff
}

for(int i=Model.Categories.OrderBy(i => i.CategoryName).Count/2; i < Model.Categories.OrderBy(i => i.CategoryName).Count; i++)
{
    // do different stuff
}
like image 41
Joshua Drake Avatar answered Sep 02 '25 15:09

Joshua Drake