List Iteration

C# Lists have many functions which allow elements iteration.

Some of them are:

  • ForEach
  • Select
  • Where
  • All
  • Aggregate

All of this functions accept lambda expression which specifies what will be done to the iterated elements.

Lambda expressions don't have any names and have the following syntax:

ForEach

Iterates the elements of a List.

It accepts a function as an argument which has a single argument - the value of the iterated element.

Let's look at the following example:

Output:

The code snippet prints all values of the List in a way specified in the lambda expression.

Select

Returns a List which elements are modified in the lambda.

Output:

In this case the modification is specified according to the returned value - value * 2.

ToList is used to convert the select function result into list.

If the lambda expression returns a single expression it can be simplified.

From this:

To this:

Output:

Where

Allows filtering specific elements.

if the lambda returns True - the element will be present in the returned List.

If the lambda returns False - it will not be present.

For example we can filter the List to return only the even numbers:

Output:

All

Allows checking if all elements match certain condition.

If all of the elements match the condition in the lambda (to return true), then the All function returns true.

If one or more of the elements don't match the condition in the lambda (to return false), then the All function returns true.

For example we can check if all of the elements in the list are even:

Output:

Aggregate

Accumulates a single value based on a lambda expression.

It has 2 arguments - the initial value and the lambda expression.

The lambda expression accepts 2 arguments - total and value in which total is the accumulated value.

An example of function summing List elements with Console.WriteLine for explanations:

Output: