我试图只为前半部分的项目迭代一个列表,然后再次我想迭代一个列表,只列出剩余的另一半列表。任何想法?
@foreach (var category in Model.Categories.OrderBy(i => i.CategoryName))
{
<li>
<div id="category_@(category.SKU)"
class="itemBlock"
onclick="toggle('@(category.SKU)')">
</li>
}
答案 0 :(得分:3)
类似的东西:
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
}
应该做的伎俩,不能保证语法是100%,但这应该给你所需要的一切!
答案 1 :(得分:2)
只需使用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
}
答案 2 :(得分:1)
我真的建议将该逻辑推送到您的模型中,然后只获取已为视图格式化的数据:
[Serializable]
public class YourModel
{
private int _mid
{
get { Categories.Count / 2; }
}
private int _top
{
get { Categories.Count - _mid; }
}
public List<Category> CategoriesLowerHalf
{
get { Categories.OrderBy(i => i.CategoryName).Take(_mid); }
}
public List<Category> CategoriesUpperHalf
{
get { Categories.OrderBy(i => i.CategoryName).GetRange(_mid, _top); }
}
// rest of your model
}
然后在你看来:
@foreach (var category in Model.CategoriesLowerHalf)
{
<li>
<div id="category_@(category.SKU)" class="itemBlock" onclick="toggle('@(category.SKU)')">category.Name</div>
</li>
}
@foreach (var category in Model.CategoriesUpperHalf)
{
<li>
<div id="category_@(category.SKU)" class="itemBlock" onclick="toggle('@(category.SKU)')">category.Name</div>
</li>
}
答案 3 :(得分:0)
也许您可以将列表拆分为2个数组,然后根据需要对每个数组运行一个循环。
答案 4 :(得分:0)
以下代码适用于我的应用。
@{
int a = 0;
int b = 0;
}
<li>
@foreach (var item in Model.NameHere)
{
//write code here
a++;
if (a == Model.Offices.Count() / 2)
{
break;
}
}
</li>
<li>
@foreach (var item in Model.NameHere)
{
if (b >= Model.Offices.Count() / 2)
{
//write code here
}
b++;
}
</li>