Tuesday, September 6, 2011

use ReSharper to refactor foreach loops to LINQ expressions

Eric Anderson illuminated that JetBrains ReSharper 6 and 5 allow one to refactor foreach loops into LINQ expressions. If you put your cursor at the word "foreach" and ReSharper sees a way to clean it up, a light bulb will appear with a drop down menu nested "inside of it" which expands upon a click. The refactorings are probably going to work better in some cases rather than others. For example, I just refactored this:

Int32 counterOfPrograms = 0;

foreach (Program program in ProgramsDTO.Entities)

{

   DateTime? startDate = program.StartDate();

   dataTable.Rows[counterOfPrograms][1] =

      (startDate != null) ? startDate.Value.Month + "/" + startDate.Value.Year : "";

   counterOfPrograms++;

}

 
 

Into this:

Int32 counterOfPrograms = 0;

foreach (DateTime? startDate in ProgramsDTO.Entities.Select(program

      => program.StartDate()))

{

   dataTable.Rows[counterOfPrograms][1] =

      (startDate != null) ? startDate.Value.Month + "/" + startDate.Value.Year : "";

   counterOfPrograms++;

}

 
 

...and it is only a marginal improvement.

Parting thought: Check out .TakeWhile here.

No comments:

Post a Comment