Monday, September 5, 2011

struggling in replacing foreach instances with lambdas

I am trying to refactor the following foreach (from here) to a select:

foreach (Program program in ProgramsDTO.Entities)

{

   dataTable.Rows[counterOfPrograms][1] = program.GoGetBaz();

   counterOfPrograms++;

}

 
 

My best effort:

var throwAwayVariable = ProgramsDTO.Entities.Select(program => dataTable.Rows[counterOfPrograms++][1] = program.GoGetBaz()).ToList();

 
 

I wish I did not have to cast to a variable I do not need. I wish I could do the following. (I cannot do the following.)

ProgramsDTO.Entities.Select(program => dataTable.Rows[counterOfPrograms++][1] = program.GoGetBaz());

 
 

In trying to clean up other foreach instances here, I have discovered that .Select can be joined to a List or an IEnumerable but not to a collection of DataRow or DataColumn. :( ...I also cannot do the following. (Cannot convert expression type 'void' to return type 'TResult')

var throwAwayVariable = columnNames.Select(columnName => dataTable.Columns.Remove(columnName)).ToList();

 
 

Which I had hoped to do to replace this:

foreach(string columnName in columnNames)

   dataTable.Columns.Remove(columnName);

No comments:

Post a Comment