ReSharper 2016.1 Help

Code Inspection: Loop can be converted into LINQ-expression

When ReSharper 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);

ReSharper 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, ReSharper 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). Another benefit is that having a LINQ expression lets you 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.

See Also

Last modified: 19 August 2016