4

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.

1

1 Answer 1

4

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++; }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.