# LINQ get tuple of sums

Page 1 of 1

## 3 Replies - 191 Views - Last Post: 23 June 2020 - 06:13 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=419561&amp;s=9c9e928644beda8bff0af83509d29587&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 andrewsw

• palpable absurdity

Reputation: 6905
• Posts: 28,565
• Joined: 12-December 12

# LINQ get tuple of sums

Posted 23 June 2020 - 03:09 AM

I'm working on this LINQ query to return a tuple, I just need the totals excluding VAT and VAT only, and I will then calculate the Gross by adding them.

So for I have this, which projects an anonymous class into the tuple:
```Tuple<decimal, decimal> result = (from invoice in Context.PMJobInvoicesReceived.AsNoTracking()
where invoice.JobNumber == jobNo
select new { totalExcludingVat = invoice.InvoiceValue ?? 0.0m, totalVat = invoice.VATAmount })
.AsEnumerable()
.Select(x => new Tuple<decimal, decimal>(x.totalExcludingVat, x.totalVat))
.FirstOrDefault();
```

I don't want the FirstOrDefault, though, I want to sum the two values. How can I "wedge in" the sums?

(It doesn't help that InvoiceValue is nullable!?)

Is This A Good Question/Topic? 0

## Replies To: LINQ get tuple of sums

### #2 andrewsw

• palpable absurdity

Reputation: 6905
• Posts: 28,565
• Joined: 12-December 12

## Re: LINQ get tuple of sums

Posted 23 June 2020 - 03:39 AM

I think I've got it now:

```            Tuple<decimal, decimal> result = (from invoice in Context.PMJobInvoicesReceived.AsNoTracking()
where invoice.JobNumber == jobNo
group invoice by 1 into gp
select new { totalExcludingVat = gp.Sum(x => x.InvoiceValue ?? 0.0m), totalVat = gp.Sum(x => x.VATAmount) })
.AsEnumerable()
.Select(x => new Tuple<decimal, decimal>(x.totalExcludingVat, x.totalVat))
.FirstOrDefault();
```

What threw me was that the original version of the query just had Sum's, no grouping. It seems the grouping is needed with a LINQ query expression.

[I think I can also now dispense with the AsEnumerable.]

### #3 Skydiver

• Code herder

Reputation: 7447
• Posts: 25,085
• Joined: 05-May 12

## Re: LINQ get tuple of sums

Posted 23 June 2020 - 06:06 AM

Since Master jon.kiparsky has taught me the ways of the Aggregate():

```var total = Context.PMJobInvoicesReceived
.AsNoTracking()
.Where(invoice => invoice.JobNumber == jobNo)
.Aggregate((excludingVAT : 0m, VAT : 0m),
(total, invoice) =>
(total.excludingVAT += invoice.InvoiceValue ?? 0m, total.VAT += invoice.VATAmount));

```

### #4 andrewsw

• palpable absurdity

Reputation: 6905
• Posts: 28,565
• Joined: 12-December 12

## Re: LINQ get tuple of sums

Posted 23 June 2020 - 06:13 AM

neat