Reputation: 10116
I have an ASP.NET Razor MVC4 view with the following @using
statement at the top to include LINQ
in the page.
@using System.Linq
Then I have a loop where I want to access specific elements of the contents of a System.Collections.Generic.Dictionary object (@Model.content)
. In this case,
element 1->last.
@for (int i = 1; i < @Model.content.Count; i++)
{
<li class="bullet">
@Model.content.ElementAt(i)
</li>
}
I am receiving the following error.
'System.Collections.Generic.Dictionary' does not contain a definition for 'ElementAt'
What do I need to do to utilize LINQ in this Razor view?
I know I could use a foreach
to iterate all the elements, but in this situation need to access specific elements.
Upvotes: 4
Views: 8090
Reputation: 245399
You could make System.Linq work for your purpose, but I would strongly suggest against it.
You'll wind up iterating your collection multiple times over using ElementAt
. As your collection grows, performance will be terrible.
You'd be far better off using a foreach loop and tracking the index yourself (please excuse the razor syntax if it's a bit off):
@{ var counter = 0; }
@foreach(var kvp in @Model.content)
{
@if(counter > 0){
<li class="bullet">
@kvp.Value
</li>
}
@{ counter++; }
}
Upvotes: 4