ReSharper
 
Get ReSharper
Get your hands on the new features ahead of the release by joining the Early Access Program for ReSharper 2025.1! Learn more

Code inspection: Loop can be converted into LINQ-expression

Last modified: 11 February 2024

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:

can be automatically converted to

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). 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.