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
).
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.
CodePudding user response:
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);
CodePudding user response:
I think all you want to do is filter it first and then add. Example:
public class O
{
public int A { get; set; }
public int? B { get; set; }
}
var initList = new List<O>
{
new O {A= 1, B = 2},
new O {A= 2},
new O {A= 3, B = 2},
};
var sum = initList.Where(item => item.B != null).Sum(item => item.A);
CodePudding user response:
Anyways, the way i'd do it is like so:
var sum = objectArray.Where(x => x.b != null).Sum(x => x.a);