Loop can be converted into a LINQ expression

Skip to end of metadata
Go to start of metadata

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 don’t have to do record-keeping related to the iteration variable — the foreach loop lets you avoid this. (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.

Labels:
None
Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.