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

c# array of objects how to sum object.a property based on object.b property

I’m using c# .NET 4.8. I have an array of objects. The objects have properties, I want to get the sum of all of one of the properties only if the other property is not null.

So if I have these 3 objects in an array:

myObject[] objectArray = [
    new myObject{ a = 1, b = 2 },
    new myObject{ a = 3 },
    new myObject{ a = 4, b = 5 }
];

I want to sum myObject.a only if myObject.b is not null, which in this case would be 5 (1 from objectArray[0].a and 4 from objectArray[2].a).

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

I’m trying to accomplish this with linq but am having an issue with figuring out the syntax to it.

I’ve tried this:

objectArray.Select(x => x.a).Where(x.b != null).Sum();

but trying to reference x.b in my Where statement gives me the following error:

Cannot resolve symbol ‘x’

I’m stuck on how to format this linq query to get the value I need. If anyone could give me some instruction on how to accomplish what I’ve outlined in this question I would greatly appreciate it. A correct, clearly explained answer will be marked as accepted and upvoted. Thanks.

>Solution :

You have forgotten that a Where expression receives the current item in the sequence enumerated. So it should be Where(x => x.b != null) but you need also to tell the Sum expression what you want to sum. The Select part is not needed at all.

So, assuming b is a nullable type (IE int? b {get;set;}) then you can get the sum of a where b is null in a simple way

var result = objectArray.Where(x => x.b != null).Sum(k => k.a);

If b is not a nullable type (IE int b {get;set;} ) then, when you don’t give it a value, it has the default value for integers (zero) so the sum could be done without any where

var result = objectArray.Sum(k => k.a);
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