JetBrains Rider 2024.1 Help

Code inspection: Loop can be converted into LINQ-expression

When JetBrains Rider determines that you are iterating an IEnumerable with a for loop, it may offer to convert this loop into a LINQ expression. For example, the following code:

int c = 1; for (int i = 0; i < numbers.Length; ++i) c *= numbers[i];

can be automatically converted to

int c = numbers.Aggregate(1, (current, t) => current*t);

JetBrains Rider is typically smart enough to identify which LINQ operators can express the operations that are defined in the loop. For example, if we had c += numbers[i] in the loop above, JetBrains Rider would reduce the expression to numbers.Sum().

But what are the advantages of this approach? Well, one is that you do not have to do record-keeping related to the iteration variable (the exception being the case where you really need the iteration variable). On top of that you have all the LINQ-specific benefits — for example, you can request the use of parallelization just by adding the .AsParallel() method call right after the collection name. This will instruct the runtime to use PLINQ (Parallel LINQ), which can speed up your calculations.

Last modified: 11 February 2024