开发者

Iterate through collection and print Index and Item in Razor

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 p开发者_Go百科roblem 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 :-(


Try like this:

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


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)


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜