asp.net-mvc 遍历集合并在 Razor 中打印索引和项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6674621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:19:48  来源:igfitidea点击:

Iterate through collection and print Index and Item in Razor

asp.net-mvcasp.net-mvc-3razor

提问by Rene

I'm having problems with my razor view. I have the following:

我的剃刀视图有问题。我有以下几点:

public ICollection<Topic> Topics

public class Topic
{
    public string Description { get; set; }
}

I want to iterate through the collection and print out the results like this:

我想遍历集合并打印出这样的结果:

    @foreach (int index in Enumerable.Range(0, Model.Topics.Count())){

        <div>@(index). Model.Topics[@(index)].Description"</div>
    }

The problem is that all I get is:

问题是我得到的只是:

0. Model.Topics[0].Description"
1. Model.Topics[1].Description"

I tried all kinds of things but still can't get the description out.

我尝试了各种方法,但仍然无法获得描述。

What am I doing wrong :-(

我究竟做错了什么 :-(

回答by Darin Dimitrov

Try like this:

像这样尝试:

@foreach (var item in Model.Topics)
{
    <div>@Model.Topics.IndexOf(item). @item.Description</div>
}

回答by gideon

This should work:

这应该有效:

@{int i = 0;}
@foreach (Topic tp in Model.Topics){
    <div>@(i++).ToString() @tp.Description</div>
}

What your doing is trying to use the foreachlike a for loop. (Possibly like a C++ iterator?) The foreach is however syntactic sugar that does all that work for you.

您所做的是尝试使用foreachfor 循环之类的方法。(可能像 C++ 迭代器?)然而,foreach 是一种语法糖,可以为您完成所有工作。

In C# foreach loops over typed collections. So if you have :

在 C# 中 foreach 循环遍历类型化集合。所以如果你有:

int[] numbers = new int[] {1,2,3,4};
Person[] persons = //collection of persons

The loops would be:

循环将是:

foreach(int n in numbers) { /*n would be each of the numbers*/  }
foreach(Person p in persons) 
    {/* p here would refer to each person per iteration*/ }

Works for anything IEnumerable (which is IList, Arrays, Collections etc)

适用于任何 IEnumerable(即 IList、数组、集合等)

回答by Mikael Eliasson

Try:

尝试:

@foreach (int index in Enumerable.Range(0, Model.Topics.Count())){

        <div>@(index). @Model.Topics[index].Description</div>
}

Or even better:

或者甚至更好:

@{ int i = 1; }
@foreach (var topic in Model.Topics){
    <div>@(i++). @topic.Description</div>
}