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?
The increment in the original
foreachloop will not affect the contents of the array, the only way to do this remains aforloop: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:
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.There is a
ForEachmethod on arrays that will allow you to use a lambda function instead of aforeachblock, though for anything more than a method call I would stick withforeach.