mercredi 18 avril 2018

Iterating over properties and use each one in a lambda expression

I am trying to simplify my code a bit by iterating over the columns in a table and use each column to map to a value instead of having multiple lines of code with a single different value. So going from this:

foreach(var n in groupedResults){
    SetCellForData("Column1", n.Sum(x => x.ColumnName1FromTable));
    SetCellForData("Column2", n.Sum(x => x.ColumnName2FromTable));
    ...
    SetCellForData("Column10", n.Sum(x => x.ColumnName10FromTable));
}

To something like this:

var columnProperties = typeof(TableClass).GetProperties().Select(t => t);
foreach(var n in groupedResults){
    foreach(var columnProperty in columnProperties ){
        SetCellForData(columnProperty.Name, n.Sum(x => x.????);
    }
}

Where the ???? part uses the columnProperty to Sum the column in the n grouped result.





Aucun commentaire:

Enregistrer un commentaire