Click here to Skip to main content
11,923,046 members (61,081 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


4 bookmarked

Cumulating values with LINQ

, 26 Jul 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
This tip describes few examples how ro cumulate values using an extension method with LINQ


Sometimes a cumulation of values is needed in a program. A typical example is calculation of cumulative sum. Here are few examples how to handle data cumulatively with LINQ.

Cumulative sum

A typical need is to calculate a cumulative sum. The LINQ doesn't directly have a method to do this, but by building a small extension method, this can be easily done.

The following extension method calculates cumulative sum for decimal numbers:

/// <summary>
/// Calculates a cumulative value for decimal numbers
/// </summary>
/// <param name="numbers">Numbers to sum</param>
/// <returns>Cumulative sum</returns>
public static System.Collections.Generic.IEnumerable<decimal> CumulativeSum(
   this System.Collections.Generic.IEnumerable<decimal> numbers) {

   decimal summedNumber = 0;

   foreach (decimal number in numbers) {
      summedNumber = summedNumber + number;
      yield return summedNumber;

The above code iterates through all the decimal numbers in the collection and for each iteration it calculates the current cumulative sum and returns it using the yield keyword.

To test the functionality let's sum some numbers:

// Array of test numbers
decimal[] numbers = new decimal[] { 1, 3, 5, 7, 11 };

// Calculate and print the cumulative sum for the numbers
System.Diagnostics.Debug.WriteLine("The cumulative sum contains the following results");
foreach (decimal partialSum in numbers.CumulativeSum()) {
   System.Diagnostics.Debug.WriteLine("   - {0}", partialSum);
System.Diagnostics.Debug.WriteLine("The cumulative sum total is {0}", numbers.CumulativeSum().Last());    

Running the code above would produce the following to the output window of Visual Studio:

The cumulative sum contains the following results
   - 1
   - 4
   - 9
   - 16
   - 27
The cumulative sum total is 27

Cumulating strings

Cumulating string values is basically the same as with numbers, so let's take a bit different kind of example.

Using the String.Split method it's easy to break a path into separate directories. But if you need to know all the valid paths in a given path, you can split the original path and then use a cumulative extension method to concatenate the directories.

/// <summary>
/// Builds a cumulative path based on directory names
/// </summary>
/// <param name="pathPart">Individual directories</param>
/// <returns>Cumulated path</returns>
public static System.Collections.Generic.IEnumerable<string> CumulativePath(
this System.Collections.Generic.IEnumerable<string> pathPart) {
   System.Text.StringBuilder concatenated = new System.Text.StringBuilder();

   foreach (string part in pathPart) {
      if (concatenated.Length != 0) {
      yield return concatenated.ToString();

The idea is almost the same as with summing the numbers. The minor difference is that since now we're playing with paths, a path separator (\) is added between directories.

To test this, consider the following

// Some random path
string somePath = @"C:\Some directory\Some subdirectory\Somefile.txt";

// Split the path and print out each cumulated portion of the path
System.Diagnostics.Debug.WriteLine("The path contains the following parts");
foreach (string partialPath in somePath.Split('\\').CumulativePath()) {
   System.Diagnostics.Debug.WriteLine("   - '{0}'", new object[] { partialPath });

Running this would produce the following output

The path contains the following parts
   - 'C:'
   - 'C:\Some directory'
   - 'C:\Some directory\Some subdirectory'
   - 'C:\Some directory\Some subdirectory\Somefile.txt'

For example if you have a path to a file and you want to test which of the directories are valid or accessible you could use a code like

// Some partially existing path
string somePath2 = @"C:\Windows\Some non-existent directory\Some non-existent file.txt";

// Split the path and print out each cumulated portion of the path
System.Diagnostics.Debug.WriteLine("The path parts are valid as follows");
foreach (string partialPath in somePath2.Split('\\').AllButLast().CumulativePath()) {
   System.Diagnostics.Debug.WriteLine("   - '{0}' does exist: {1}", 

This would result to

The path parts are valid as follows
   - 'C:' does exist: True
   - 'C:\Windows' does exist: True
   - 'C:\Windows\Some non-existent directory' does exist: False


  • July 26, 2012: Tip created.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Finland Finland
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralMy vote of 5 Pin
Maciej Los12-Apr-15 0:29
protectorMaciej Los12-Apr-15 0:29 
GeneralRe: My vote of 5 Pin
Mika Wendelius13-Apr-15 18:41
mentorMika Wendelius13-Apr-15 18:41 
GeneralNeat example, illustration useful techniques Pin
Espen Harlinn30-Jul-12 12:26
mvpEspen Harlinn30-Jul-12 12:26 
GeneralMy vote of 1 Pin
Jasper4C#29-Jul-12 22:25
memberJasper4C#29-Jul-12 22:25 
GeneralRe: My vote of 1 Pin
Mika Wendelius30-Jul-12 3:12
mvpMika Wendelius30-Jul-12 3:12 
QuestionLinq Aggregation is already build in Pin
Jasper4C#29-Jul-12 22:25
memberJasper4C#29-Jul-12 22:25 
AnswerRe: Linq Aggregation is already build in Pin
Mika Wendelius30-Jul-12 3:10
mvpMika Wendelius30-Jul-12 3:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.151125.3 | Last Updated 26 Jul 2012
Article Copyright 2012 by MikaW
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid