This post will discuss how to apply a function to each element in a list in C#.

1. Using Select() Method

The LINQ’s Enumerable.Select() extension method projects each element of a sequence into a new form. The following code example demonstrates how you can use the Select() to apply the ToString() function to each element in a list.

Download  Run Code

 
Alternatively, if you prefer LINQ syntax:

Download  Run Code

2. Using ParallelEnumerable.ForAll() Method

LINQ also provides the ParallelEnumerable.ForAll() method, which invokes the specified action for each element in the source, in parallel. This will not modify the original list and can be used as follows:

Download  Run Code

3. Using List<T>ForEach() Method

Alternatively, you can use the List<T>ForEach() function to call a specified action for each item in a list. Similar to the ForAll() method, this will not modify the source list.

Download  Run Code

That’s all about applying a function to each element in a list in C#.