AgainMe AgainMe - 1 month ago 10
C# Question

Convert all properties value of a specific object type with Math.Round?

I've a specific object type with this structure:

public class PoissonFullTime
{
public double HomeWin { get; set; } //1
public double Draw { get; set; } //X
public double AwayWin { get; set; } //2
public double HomeWinDraw { get; set; } //1X


now calling a specific method I get the properties valorized like this:

enter image description here

this values are stored inside this object:

var fullTimeForecast = poisson.GetFullTimeForecast();


is possible iterate to each properties of
fullTimeForecast
and convert the value into
Math.Round(value, 2)
? Thanks.

Answer

Reflection will help to solve your problem, it will update all objects's properties with type double using Math.Round (fiddle):

var fullTimeForecast = new PoissonFullTime { AwayWin = 123.3123123 };
fullTimeForecast.GetType().GetProperties()
    .Where(x => x.PropertyType == typeof(double)).ToList()
    .ForEach(x => x.SetValue(
            fullTimeForecast, 
            Math.Round((double)x.GetValue(fullTimeForecast), 2)
        )
    );