An increment of the source foreach does not affect the contents of the array, the only way to do this is with 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. You can achieve the above code with Linq, although it is slightly contrary to its objectives:
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 the equivalent), as shown in some other answers, excludes from the resulting sequence any values less than or equal to 3.
var intArray = new int[] { 10, 1, 20, 2 }; var newArray = from i in intArray where i > 3 select i + 1;
There is a foreach method on arrays that will allow you to use a lambda function instead of a foreach block, although for something more than a method call, I would stick with foreach .
intArray.ForEach(i => DoSomething(i));
Zooba
source share