LINQ sumWhere
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: LINQ sumWhere

  1. #1
    Join Date
    Jun 2001
    Location
    Melbourne/Aus (C# .Net 4.0)
    Posts
    686

    LINQ sumWhere

    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?
    Rob
    -
    Ohhhhh.... Old McDonald was dyslexic, E O I O EEEEEEEEEE.......

  2. #2
    Join Date
    Jun 2001
    Location
    Melbourne/Aus (C# .Net 4.0)
    Posts
    686

    Re: LINQ sumWhere

    Seems I worked it out....

    Code:
    _myArray.Sum(a => a.Equals(n) ? a : 0);
    or in my case which has an array of objects with an Int32 Value member.

    Code:
    _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...
    Last edited by rliq; August 19th, 2009 at 01:33 AM.
    Rob
    -
    Ohhhhh.... Old McDonald was dyslexic, E O I O EEEEEEEEEE.......

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center