Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.

Follow publication

Member-only story

C#: LINQ Expressions with Enumerable Class (Part 4)

--

Sum

The Sum method is used to calculate the sum of a sequence of numeric values.

It is an aggregation method that operates on a collection, such as an array, list, or any other enumerable, and returns the total sum of the elements in that collection.

In our example, we first calculate the sum of the numbers from the list, and then we calculate the total sum of the pet ages.

var numbers = new[] { 70, 30, 100, 10, 90, 50, 20, 80, 60, 40 };

var totalSum = numbers.Sum();
Console.WriteLine(totalSum); // 550

var pets = new List<Pet>
{
new("Whiskers", PetType.Cat, Color.Gray, 3),
new("Rex", PetType.Dog, Color.Brown, 5),
new("Bubbles", PetType.Fish, Color.Orange, 1),
new("Mittens", PetType.Cat, Color.Black, 2),
new("Fido", PetType.Dog, Color.White, 4),
new("Goldie", PetType.Fish, Color.Gold, 2)
};

var totalAge = pets.Sum(p => p.Age);
Console.WriteLine(totalAge); // 17

ElementAt

The ElementAt method retrieves an element at a specific index from a sequence. The method works with both IEnumerable<T> to Objects and IQueryable<T>.

If you want to avoid the exception and return a default value when the index is out of range, you can use ElementAtOrDefault, which returns the default value of the element type (e.g., null for reference types, 0 for integers) when the index is out of bounds.

Single

The Single method returns the only sequence element that satisfies a specified condition.

An exception is thrown if no element or more than one element satisfies the condition.

var numbers = new[] { 70, 30, 100, 10, 90, 50, 20, 80, 60, 40 };
Console.WriteLine(numbers.Single(num => num > 90)); // 100

// var numbers = new[] { 70, 30, 100, 10, 90, 50, 20, 80, 60, 40 };
Console.WriteLine(numbers.Single(num => num > 20)); // Exception: Sequence contains more than one matching element

SingleOrDefault

This method is used to retrieve a single element from a sequence that satisfies a specified condition.

If no element satisfies the condition, it returns the default value for the type. If…

--

--

Published in Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.

Written by Tomas Svojanovsky

I'm a full-stack developer. Programming isn't just my job but also my hobby. I like developing seamless user experiences and working on server-side complexities

No responses yet

Write a response