Iterate through collection and print Index and Ite

2019-02-11 01:55发布

问题:

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