Apply a function to each element in a List in C#
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4, 5 }; IEnumerable<string> strings = nums.Select(i => i.ToString()); Console.WriteLine(String.Join(", ", strings)); // 1, 2, 3, 4, 5 } } |
Alternatively, if you prefer LINQ syntax:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4, 5 }; IEnumerable<string> strings = from i in nums select i.ToString(); Console.WriteLine(String.Join(", ", strings)); // 1, 2, 3, 4, 5 } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4, 5 }; nums.AsParallel().ForAll(Console.WriteLine); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4, 5 }; nums.ForEach(Console.WriteLine); } } |
That’s all about applying a function to each element in a list in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)