3

我试图只为前半部分的项目迭代一个列表,然后我想再次为列表的剩余另一半迭代一个列表。有任何想法吗 ?

@foreach (var category in Model.Categories.OrderBy(i => i.CategoryName))
{
  <li>
    <div id="category_@(category.SKU)" 
         class="itemBlock" 
         onclick="toggle('@(category.SKU)')">
  </li>
}
4

5 回答 5

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%,但这应该给你所有你需要做的!

于 2012-04-19T15:58:29.690 回答
2

只需使用for 循环

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
}
于 2012-04-19T15:57:08.430 回答
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>
 }
于 2012-04-19T16:59:55.673 回答
0

也许您可以将列表拆分为 2 个数组,然后根据需要在每个数组上运行一个循环。

于 2012-04-19T15:53:45.643 回答
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>
于 2015-04-19T21:12:11.490 回答