Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sum up in a list of list properties

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading