Seiche
Seiche

Reputation: 3

Use IEnumerable.Sum to subtract in LINQ

I've been trying to figure out if there was a way to use IEnumerable's Sum method to subtract two values instead of adding them up?

IEnumerable<T> list = first
    .Concat(second)
    .GroupBy(x => new { x.crita, x.critb})
    .Select(y => new T
    {
        //other fields//
        vara= y.Sum(z => z.vara),
        varb= y.Sum(z => z.varb),
        varc= y.Sum(z => z.varc),
        vard= y.Sum(z => z.vard)
    });

I'm using this method to get sums between the two IEnumerables I've joined, but I was hoping to be able to subtract them too.

Any help would be really appreciated.

Also, if someone could tell me how to get products and quotients, that'd be awesome!

Upvotes: 0

Views: 752

Answers (1)

dotNET
dotNET

Reputation: 35400

Aggregate is the elder brother of Sum that can do subtract and other aggregations too. On the other hand if you want to do element-by-element subtraction, you can use general Select projections.

Reading your comment, one easy trick would be to create a projection of your second IEnumerable that negates vara, varb etc. and then use the same Sum function to compute the aggregates of groups. So basically you would just be doing a + (-b) instead of a - b. Something on the following lines:

IEnumerable<T> list = first
                  .Concat(second.Select(n => new T() { vara = -n.vara...} )
                  .GroupBy(x => new { x.crita, x.critb})
                  .Select(y => new T
                  {
                      //other fields//
                      vara= y.Sum(z => z.vara),
                      varb= y.Sum(z => z.varb),
                      varc= y.Sum(z => z.varc),
                      vard= y.Sum(z => z.vard)
                  });

Upvotes: 3

Related Questions