LINQ
query
columns
sum
programming

Get sum of two columns in one LINQ query

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In LINQ, “sum of two columns” can mean two different things: adding two fields for each row, or computing one total that includes both fields across all rows. The correct query depends on which of those results you actually need. The good news is that both cases are straightforward once you are explicit about whether the addition happens inside the row projection or inside the final aggregation.

Summing Two Fields Per Row

If each record has two numeric properties and you want their combined value per record, project a new value.

csharp
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5public class OrderLine
6{
7    public decimal Price { get; set; }
8    public decimal Tax { get; set; }
9}
10
11var items = new List<OrderLine>
12{
13    new OrderLine { Price = 10m, Tax = 1m },
14    new OrderLine { Price = 20m, Tax = 2m }
15};
16
17var perRowTotals = items.Select(x => x.Price + x.Tax).ToList();
18
19Console.WriteLine(string.Join(", ", perRowTotals));

This produces one number per row. It does not yet produce a single grand total.

One Grand Total in a Single Query

If the goal is “sum both columns across the whole sequence,” the usual query is:

csharp
decimal total = items.Sum(x => x.Price + x.Tax);
Console.WriteLine(total);

This is the most direct answer for many LINQ questions. Each row contributes Price + Tax, and Sum aggregates those row-level values into one result.

Mathematically, this is equivalent to:

csharp
decimal total = items.Sum(x => x.Price) + items.Sum(x => x.Tax);

but the single-query version is clearer and avoids traversing the collection twice in LINQ to Objects.

Query Syntax Versus Method Syntax

LINQ query syntax does not have a dedicated sum form for every shape, so method syntax is often simpler for aggregation. Still, you can combine projection with aggregation cleanly.

csharp
1var total =
2    (from item in items
3     select item.Price + item.Tax)
4    .Sum();
5
6Console.WriteLine(total);

This is still one logical LINQ query. Whether you prefer this or items.Sum(x => x.Price + x.Tax) is mostly a readability choice.

Grouped Sums

A more realistic case is summing two columns per group, such as totals by customer or category.

csharp
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5public class Sale
6{
7    public string Region { get; set; } = "";
8    public decimal Revenue { get; set; }
9    public decimal Shipping { get; set; }
10}
11
12var sales = new List<Sale>
13{
14    new Sale { Region = "East", Revenue = 100m, Shipping = 10m },
15    new Sale { Region = "East", Revenue = 50m, Shipping = 5m },
16    new Sale { Region = "West", Revenue = 80m, Shipping = 8m }
17};
18
19var totalsByRegion = sales
20    .GroupBy(x => x.Region)
21    .Select(g => new
22    {
23        Region = g.Key,
24        Total = g.Sum(x => x.Revenue + x.Shipping)
25    });
26
27foreach (var row in totalsByRegion)
28{
29    Console.WriteLine($"{row.Region}: {row.Total}");
30}

The pattern stays the same: define the per-row expression, then aggregate it at the correct scope.

Null Handling

If either column is nullable, make the null behavior explicit. Otherwise you may get unexpected null results or provider translation issues.

csharp
1public class Invoice
2{
3    public decimal? Amount { get; set; }
4    public decimal? Fee { get; set; }
5}
6
7var invoices = new List<Invoice>
8{
9    new Invoice { Amount = 10m, Fee = null },
10    new Invoice { Amount = null, Fee = 2m }
11};
12
13decimal total = invoices.Sum(x => (x.Amount ?? 0m) + (x.Fee ?? 0m));
14Console.WriteLine(total);

Using the null-coalescing operator makes the business rule visible: missing values are treated as zero.

LINQ to Objects Versus LINQ Providers

If you are querying an in-memory collection, almost any valid C# expression inside Sum works. With LINQ providers such as Entity Framework, the expression must also be translatable to SQL or another backend query language.

This usually works well:

csharp
var total = db.Orders.Sum(x => x.Subtotal + x.Tax);

But once you start calling custom helper methods inside the expression, translation may fail. For database-backed queries, keep the aggregation expression simple and provider-friendly.

Performance and Readability

items.Sum(x => x.Col1 + x.Col2) is not just concise. It communicates the intended result better than computing two separate sums and combining them later. That matters in review because there is less room for misunderstanding about traversal count or grouping level.

If the query becomes more complex, extract intermediate names rather than compressing everything into a single unreadable chain.

Common Pitfalls

The biggest mistake is not being clear about whether you want a per-row sum or a grand total. Another common issue is writing two separate Sum calls when a single Sum over a combined expression is clearer. Nullable numeric fields also cause trouble when null semantics are left implicit. In LINQ providers such as Entity Framework, complex helper methods inside the aggregation expression can fail to translate and should be avoided.

Summary

  • Use Select(x => x.A + x.B) when you want a sum per row.
  • Use Sum(x => x.A + x.B) when you want one total across the sequence.
  • Group first, then sum, when totals are needed per category or key.
  • Handle nullable columns explicitly with ?? if missing values should count as zero.
  • Keep aggregation expressions simple when the query must translate to SQL.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.