Click to See Complete Forum and Search --> : LINQ sumWhere


rliq
August 19th, 2009, 12:22 AM
I have an array of Int32's. I want to get a total sum of the number N's from that array. Not the number of N's but the sum of the N's. And I want to do it using a LINQ expression.

e.g:

If the array contains: { 3, 9, 3, 8, 6, 3, 2, 2, 3 }

if N = 3 the expression should return 12 (because there are four 3's in the array and 3 x 4 = 12)

if N = 2 the expression should return 4 (because there are two 2's in the array and 2 x 2 = 4)

Sorry about the Maths lesson, but it's best to be clear!

Anyone?

rliq
August 19th, 2009, 01:31 AM
Seems I worked it out....


_myArray.Sum(a => a.Equals(n) ? a : 0);

or in my case which has an array of objects with an Int32 Value member.


_myObjectArray.Sum(o => o.Value.Equals(n) ? o.Value : 0);


Is there a neater way?

On another point... does anyone else use the tertiary operator and find that 90% of the time, one of the then/else values is the same as the if value?

Eg (upperbound of a value):

return (a > 25 ? 25 : a);

I always think there should be a binary operator equivelent, so you could remove the ": a" from the end of the above.

Eg:

return (a > 25 ? 25);

should do the same. From my C -> C++ -> C# days, I've always thought this. Maybe my coding style... I don't know...