Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacement for for... if array iteration

I love list comprehensions in Python, because they concisely represent a transformation of a list.

However, in other languages, I frequently find myself writing something along the lines of:

foreach (int x in intArray)
  if (x > 3) //generic condition on x
    x++ 
    //do other processing

This example is in C#, where I'm under the impression LINQ can help with this, but is there some common programming construct which can replace this slightly less-than-elegant solution? Perhaps a data structure I'm not considering?

like image 686
pbh101 Avatar asked Aug 16 '08 22:08

pbh101


People also ask

Can we use any alternatives of array?

T-SQL doesn't support arrays (groups of objects that have the same attributes and that you can use techniques such as subscripting to address individually). But you can use local or global temporary tables, which the main article describes, as an alternative to an array.

Can you use for in loops for arrays?

For Loop to Traverse Arrays. We can use iteration with a for loop to visit each element of an array. This is called traversing the array. Just start the index at 0 and loop while the index is less than the length of the array.

Is map better than for loop?

map generates a map object, for loop does not return anything. syntax of map and for loop are completely different. for loop is for executing the same block of code for a fixed number of times, the map also does that but in a single line of code.


1 Answers

The increment in the original foreach loop will not affect the contents of the array, the only way to do this remains a for loop:

for(int i = 0; i < intArray.Length; ++i)
{
    if(intArray[i] > 3) ++intArray[i];
}

Linq is not intended to modify existing collections or sequences. It creates new sequences based on existing ones. It is possible to achieve the above code using Linq, though it is slightly against its purposes:

var newArray1 = from i in intArray select ((i > 3) ? (i + 1) : (i));
var newArray2 = intArray.Select(i => (i > 3) ? (i + 1) : (i));

Using where (or equivalent), as shown in some of the other answers, will exclude any values less than or equal to 3 from the resulting sequence.

var intArray = new int[] { 10, 1, 20, 2 };
var newArray = from i in intArray where i > 3 select i + 1;
// newArray == { 11, 21 }

There is a ForEach method on arrays that will allow you to use a lambda function instead of a foreach block, though for anything more than a method call I would stick with foreach.

intArray.ForEach(i => DoSomething(i));
like image 60
Zooba Avatar answered Sep 18 '22 15:09

Zooba