Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# LINQ Sum: Syntax, Edge Cases, and Performance

Learn how to use the C# LINQ Sum method with code examples, including selector overloads, empty and nullable sequences, and when to choose Aggregate.

~4 min readC#
#C##LINQ#Sum#Aggregate
Illustration of a C# LINQ Sum operation showing a collection of numbers being totaled into a single result.

The LINQ Sum method in C# totals a sequence of numeric values. It is part of the System.Linq namespace. This article covers the syntax, behavior with empty and nullable sequences, and performance considerations for large collections.

The basic syntax of Sum

The simplest form of Sum operates on a sequence of numeric values such as int, double, decimal, or their nullable counterparts. Because Sum is an extension method, add using System.Linq; to your file.

csharp
using System; using System.Linq; int[] numbers = { 1, 2, 3, 4, 5 }; int total = numbers.Sum(); Console.WriteLine(total); // Output: 15

For a non-nullable sequence with no elements, this overload returns 0. The same pattern works for List<int>, IEnumerable<double>, and other numeric collections. In LINQ to Objects, integral overloads use checked arithmetic, so an overflowing sum throws OverflowException. For float input, the result is float; for double input, it is double; for decimal, it is decimal.

Summing a projected property with a selector

When you have a sequence of objects, use the selector overload to sum a numeric property without first calling Select.

csharp
public class Order { public int Id { get; set; } public decimal Amount { get; set; } public decimal? Discount { get; set; } } List<Order> orders = new List<Order> { new Order { Id = 1, Amount = 10.5m }, new Order { Id = 2, Amount = 20.75m }, new Order { Id = 3, Amount = 5.25m } }; decimal totalAmount = orders.Sum(o => o.Amount); Console.WriteLine(totalAmount); // Output: 36.50

The selector is a Func<TSource, TResult> where TResult is one of the numeric types accepted by the Sum overloads. If the selected property is nullable, a direct Sum call ignores null elements. Use the null-coalescing operator when you want to treat null as zero:

csharp
decimal? totalDiscount = orders.Sum(o => o.Discount ?? 0m);

This returns 0m when the sequence is empty or every discount is null.

Empty sequences and nullable types

For non-nullable numeric types, an empty sequence produces 0. For nullable numeric types, Sum returns null when the sequence is empty or when all elements are null. If a sequence contains a mixture of values and null, Sum ignores the null values.

csharp
int?[] nullableNumbers = { 1, null, 3 }; int? nullableSum = nullableNumbers.Sum(); Console.WriteLine(nullableSum); // Output: 4 int?[] allNull = { null, null }; int? emptySum = allNull.Sum(); Console.WriteLine(emptySum == null); // Output: True

For a collection of nullable values, you can also convert nulls to zero in the selector:

csharp
int?[] numbers = { 1, null, 3 }; int total = numbers.Sum(n => n ?? 0); Console.WriteLine(total); // Output: 4

Performance considerations for large collections

Sum enumerates a sequence once and does not parallelize automatically. If you need to sum a filtered subset, Where(...).Sum(...) still makes a single pass over the source while applying the predicate; it does not require an intermediate list. A hand-written loop can be marginally faster in a very hot path because it avoids the delegate call per item, but the LINQ version is usually clear enough unless profiling shows a problem.

For floating-point types, the order of addition can affect the result because of rounding. LINQ to Objects enumerates source order, so a large sequence of double values with widely different magnitudes can accumulate rounding error. For financial calculations, prefer decimal to avoid binary floating-point precision issues.

Because the integral Sum overloads use checked arithmetic, an overflowing sum throws an exception. If you are summing int values that might exceed int.MaxValue, project to long first. If you need a different overflow strategy, Aggregate gives you more control, but this is rarely necessary.

When to use Aggregate instead of Sum

The Aggregate method is a more general version of Sum. It applies an accumulator function to each element and returns the final result. You can use it for custom accumulation logic, such as calculating a product or building a custom aggregate object.

csharp
int[] numbers = { 1, 2, 3, 4 }; int total = numbers.Aggregate((acc, x) => acc + x);

This works, but Aggregate without a seed throws an InvalidOperationException on an empty sequence, whereas Sum returns 0. If you need the empty-sequence behavior, provide a seed:

csharp
int total = numbers.Aggregate(0, (acc, x) => acc + x);

For simple summation, Sum is clearer because it is a specialized implementation. Aggregate is the right choice when you need to combine elements in a way Sum does not support, such as calculating a product or performing a running calculation that depends on previous state.

OperationSumAggregate
Empty sequenceReturns 0 (null for nullable types)Throws without a seed; returns seed if provided
Nullable elementsIgnores null valuesDepends on accumulator
OverflowThrows in checked context for integral typesDepends on accumulator implementation
ReadabilityHigh for simple summationLower for simple summation

Common mistakes and pitfalls with Sum

One common mistake is assuming that Sum accepts string values. It does not; the compiler rejects the call because no overload accepts string. Use string.Join or a StringBuilder to concatenate text.

Another issue is expecting Sum to widen the result type. Summing int values returns int, so a large collection can overflow. If you need a long result from an int sequence, project the elements first:

csharp
long total = numbers.Sum(x => (long)x);

This avoids overflow for large integer collections. Summing decimal values returns decimal, and summing float values returns float.

Finally, with IQueryable<T> sources, Sum is handled by the LINQ provider. A provider such as Entity Framework may translate it into a SQL aggregate, so behavior can depend on the provider and database.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.