Summing the elements of a sequence with LINQ C#

Say you have the following numeric sequence:

IEnumerable<int> integers = Enumerable.Range(1, 100);

If you don’t know what the Range operator does, then start here.

You can find the sum of the elements in the sequence using the Sum LINQ operator:

int sum = integers.Sum();

…which gives 5050. The Sum operator obviously only works with numeric elements such as int, long, decimal and double. You can sum specific elements of an object using the overloaded Sum operator.

Take the following objects:

public class Concert
{
	public int SingerId { get; set; }
	public int ConcertCount { get; set; }
	public int Year { get; set; }
}

IEnumerable<Concert> concerts = new List<Concert>()
			{
				new Concert(){SingerId = 1, ConcertCount = 53, Year = 1979}
				, new Concert(){SingerId = 1, ConcertCount = 74, Year = 1980}
				, new Concert(){SingerId = 1, ConcertCount = 38, Year = 1981}
				, new Concert(){SingerId = 2, ConcertCount = 43, Year = 1970}
				, new Concert(){SingerId = 2, ConcertCount = 64, Year = 1968}
				, new Concert(){SingerId = 3, ConcertCount = 32, Year = 1960}
				, new Concert(){SingerId = 3, ConcertCount = 51, Year = 1961}
				, new Concert(){SingerId = 3, ConcertCount = 95, Year = 1962}
				, new Concert(){SingerId = 4, ConcertCount = 42, Year = 1950}
				, new Concert(){SingerId = 4, ConcertCount = 12, Year = 1951}
				, new Concert(){SingerId = 5, ConcertCount = 53, Year = 1983}
			};

You can get the total number of concerts in the collection by specifying the property selector in a lambda expression as follows:

int allConcerts = concerts.Sum(c => c.ConcertCount);

…which yields 557.

View the list of posts on LINQ here.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: