how to replace foreach loop with for loop

I am looking for a proper syntax. I am using MVC and in my view I need to loop through the model since I need to do some other things at different counts. I am a novice here and looked through tons of postings but didn't find the syntax. Here is the code, which works:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcMysurvey.Models.Mysurvey>>" %>
<% foreach (var item in Model) {%>
            <%: Html.HiddenFor(m => item.ID) %>

And here is the code I need the syntax for to make it working:

   <% for (int i = 0; i < Model.Count(); i++) {%>
             <%: Html.HiddenFor(m => m[i].ID) %>

Answers


Your model is of type IEnumerable<MvcMysurvey.Models.Mysurvey>.

The problem is that IEnumerable<T> does not expose an indexer ([]) operator. You have two options for dealing with this inconvenience.

  1. Use an array or a list instead. Arrays and IList<T> implementations do expose an indexer operator. To use the indexer syntax, you need to convert your model to an array or other IList<T>. So, just change your

    <% for (int i = 0; i < Model.Count(); i++) {%>
       <%: Html.HiddenFor(m => m[i].ID) %>
    

    to

    <% var items = Model.ToArray();
       for (int i = 0; i < items.Length; i++) {%>
          <%: Html.HiddenFor(m => items[i].ID) %>
    
  2. Use the the ElementAt method method

    While IEnumerable<T> does not expose an indexer operator, there is a LINQ extension method that does the same thing. It is the ElementAt method. To use this syntax, you could change your code to:

     <% for (int i = 0; i < Model.Count(); i++) {%>
        <%: Html.HiddenFor(m => m.ElementAt(i).ID) %>
    

The array syntax will be almost certainly be more efficient though.


I think this may be what you're looking for? Your question isn't too clear but it sounds like you're looking to do something based on a condition that the count is equal to something. If that's the case you only need to add an if statement to check the count against whatever value you're looking for.

<% for (int i = 0; i < Model.Count(); i++)
<% { %>
    <% if (i == someCount) %>
    <% { %>
        <!-- Do Something Here -->
    <% } %>
    <%: Html.HiddenFor(m => m[i].ID) %>
<% } %>

Need Your Help

Basic ARIA landmark roles are not recognized by screen readers

html html5 accessibility wai-aria

I'm researching the implementation of ARIA with HTML5 and have built a tech demo on my localhost to manage scope before exporting to a production website.

Simple htaccess trick

php .htaccess

I want to make example.org/fish and get the tag, but however, my script get the tag wrong. Here is my htacess;