How to Use LINQ Sum in C# for Simple and Complex Collections
Use
LINQ Sum in C# to add all numeric values in a collection easily by calling Sum() on the collection or using a selector function for complex types. It returns the total sum as a single number.Syntax
The Sum() method can be used in two main ways:
- Simple collection:
collection.Sum()sums all numeric elements. - Complex collection:
collection.Sum(item => item.Property)sums a specific numeric property from each item.
This method works on collections like arrays, lists, or any IEnumerable<T> where T is numeric or you provide a selector.
csharp
var numbers = new List<int> {1, 2, 3, 4}; int total = numbers.Sum(); var people = new List<Person> { new Person { Age = 20 }, new Person { Age = 30 } }; int ageSum = people.Sum(p => p.Age);
Example
This example shows how to sum simple numbers and sum a property from objects in a list using LINQ Sum().
csharp
using System; using System.Collections.Generic; using System.Linq; class Person { public int Age { get; set; } } class Program { static void Main() { var numbers = new List<int> { 5, 10, 15 }; int totalNumbers = numbers.Sum(); Console.WriteLine($"Sum of numbers: {totalNumbers}"); var people = new List<Person> { new Person { Age = 25 }, new Person { Age = 35 }, new Person { Age = 40 } }; int totalAge = people.Sum(p => p.Age); Console.WriteLine($"Sum of ages: {totalAge}"); } }
Output
Sum of numbers: 30
Sum of ages: 100
Common Pitfalls
Common mistakes when using Sum() include:
- Calling
Sum()on an empty collection without a default value can cause an exception for nullable types. - Using
Sum()on non-numeric types without a selector causes compile errors. - For complex objects, forgetting to provide a selector function to specify which property to sum.
Always ensure the collection contains numeric values or use a selector to extract numeric properties.
csharp
var emptyList = new List<int>(); // int sumEmpty = emptyList.Sum(); // This returns 0 safely for int var people = new List<Person>(); // int sumAge = people.Sum(); // Compile error: no parameterless Sum for Person // Correct way: int sumAge = people.Sum(p => p.Age);
Quick Reference
| Usage | Description | Example |
|---|---|---|
| Sum simple numbers | Adds all numbers in a numeric collection | numbers.Sum() |
| Sum property values | Adds a numeric property from objects | people.Sum(p => p.Age) |
| Empty collection | Returns 0 for value types | emptyList.Sum() |
| Nullable types | Returns null if all elements are null | nullableList.Sum() |
Key Takeaways
Use
Sum() to add all numeric values in a collection quickly.For collections of objects, provide a selector function to sum a specific numeric property.
Calling
Sum() on empty collections returns 0 for value types safely.Avoid using
Sum() on non-numeric collections without a selector to prevent errors.LINQ Sum works on any
IEnumerable<T> with numeric types or selectors.