Replacing for Loop with Foreach Loop

how to replace foreach loop with for loop

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.

how to replace for loop by forEach

You don't need to use for or forEach if you want to detect is number presented. You can use streams with i.e. .anyMatch() method.

In example:

String number = "123";    
List<Summary> smryList = smryListResponse.getSummaryList();
boolean isNumberPresent = smryList
.stream()
.anyMatch(summary -> summary.getNumber().equals(number));
if (isNumberPresent) {
// ...
}

Also, you can try do that with other stream methods, i.e. .filter() or other. But I prefer to use .anyMatch().

Remark: streams and lambda expressions works only with Java 8 or later.
Otherwise use already posted solution

How to use replace for loop using forEach in JavaScript?

You say you need to replace the loop with an array method. The usual rationale for that (or so I teach my students) is that the array methods more clearly document what you're trying to do. If you have a for loop used to find the first value to match some condition, you should use .find. If you want to find all matching values, use .filter. If you want a item-by-item transformation, use .map. If you want to check that every item matches a given condition, use .every. If you want to check that some items match a condition, use .some. And if you want to transform the array down to a single value, use .reduce.

Note what isn't in this list: forEach. While there's nothing wrong with forEach, it doesn't really add any useful semantics. It's mostly helpful when the function passed to forEach is independently reusable, and you don't fit any of the categories above.

Let's look at what you want to do. You are transforming the points into magnitudes and then choosing the maximum. We could do this by using map for the transform, then using Math.max to find the maximum. It would look like this:

const points = [{x: 1, y: 2}, {x: 8, y: 6}, {x: 7, y: 5}, {x: 3, y: 0}]

const max_magnitude = Math .max (0, ... points .map (({x, y}) => x * x + y * y))

console .log (max_magnitude) //=> 100 (8 * 8 + 6 * 6)

Replace a for loop with foreach in r

Here is a simple foreach loop using the sequential %do% operator.

Note that the first 2 values of vector file are the output of print.

library(foreach)

file <- c("/data/an_01h.dat", "/data/an_01h.dat")
foreach (f=file) %do% {
print(f)
}
#> [1] "/data/an_01h.dat"
#> [1] "/data/an_01h.dat"
#> [[1]]
#> [1] "/data/an_01h.dat"
#>
#> [[2]]
#> [1] "/data/an_01h.dat"

Created on 2022-04-21 by the reprex package (v2.0.1)


And a parallelized loop. The %dopar% operator is a parallelizable operator. This time print doesn't show its output, see this SO question on this.

library(foreach)
library(doParallel)
#> Loading required package: iterators
#> Loading required package: parallel

file <- c("/data/an_01h.dat", "/data/an_01h.dat")

ncores <- detectCores() - 1L
registerDoParallel(ncores) # use multicore, set to the number of our cores
foreach (f=file) %dopar% {
print(f)
}
#> [[1]]
#> [1] "/data/an_01h.dat"
#>
#> [[2]]
#> [1] "/data/an_01h.dat"

Created on 2022-04-21 by the reprex package (v2.0.1)

replace Foreach - For

I don't understand why you want to get rid of forEach, but you have the answer and it's simple as this:

for (let i = 0; i < images.length; i++) {
const oImage = new Image();
oImage.onload = () => {
ctx.drawImage(oImage, i * 100, 0, 100, 100);
};

oImage.src = images[i].textContent;
}


Related Topics



Leave a reply



Submit