Iterate through collection and print Index and Item in Razor

大憨熊 提交于 2019-12-18 18:09:34

问题


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 :-(


回答1:


Try like this:

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



回答2:


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 foreach like a for loop. (Possibly like a C++ iterator?) The foreach is however syntactic sugar that does all that work for you.

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

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)




回答3:


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>
}


来源:https://stackoverflow.com/questions/6674621/iterate-through-collection-and-print-index-and-item-in-razor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!