Home > front end >  Sum up in a list of list properties
Sum up in a list of list properties

Time:11-17

I have below structure where I would like to sum up a list of properties

public class Space
{       
    public AirBalance AirBalance { get; set; } = new();      
}

public class AirBalance
{
    public bool AllowVariableExhaust { get; set; }
    public SpaceVentilationAirflow VentilationAirflow { get; set; } = new();
}
public class SpaceVentilationAirflow 
{
    public List<A621VentilationAirflow> A621VentilationAirflows { get; set; } = new();
}

public class A621VentilationAirflow 
{
    public double BreathingZoneVentilation { get; set; }
}

I am trying to sum up all spaces of A621VentilationAirflow's BreathingZoneVentilation, and I have a value of 1115.05 for breathing zone ventilation. When I sum up using the below code, it always gives me the same value even If I have two spaces and a list of A621VentilationAirflow objects that exist.

 Spaces?.Sum(a => a?.AirBalance?.VentilationAirflow?.A621VentilationAirflows.Sum(a => a.BreathingZoneVentilation))

Could anyone please let me know where I am doing wrong with the above code? Many thanks in advance

CodePudding user response:

I feel like you need to change your code to:

 Spaces?.Sum(a => a?.AirBalance?.VentilationAirflow?.A621VentilationAirflows.Sum(b => b.BreathingZoneVentilation))

Also, using projection (Select / SelectMany) you can get a more readable (imo) query:

        var y = spaces
            .Select(c => c.AirBalance)
            .Select(c => c.VentilationAirflow)
            .SelectMany(c => c.A621VentilationAirflows)
            .Sum(c => c.BreathingZoneVentilation);

https://dotnetfiddle.net/RBX9aX

  •  Tags:  
  • c#
  • Related