ZetCode

C# List ConvertAll

last modified July 5, 2023

This tutorial demonstrates how to use the C# List ConvertAll method to transform all elements of a list into another type. It provides practical examples to illustrate various conversion scenarios.

A C# List is a dynamic collection of elements of the same type, accessible by index. The ConvertAll method enables efficient conversion of each element to a new type, creating a new list without modifying the original.

public List<TOutput> ConvertAll<TOutput>(Converter<T, TOutput> converter);

The TOutput parameter specifies the type of elements in the resulting list. The Converter delegate defines the logic to transform each element from the source type (T) to the target type (TOutput).

ConvertAll returns a new List<TOutput> containing the converted elements. It is useful for tasks like type casting, data transformation, or deriving new values from existing list elements.

Converting Integers to Decimals

This example uses ConvertAll to convert a list of integers into a list of decimals, showcasing a simple type conversion.

Program.cs
List<int> vals = [1, 2, 3, 4, 5];
List<decimal> res = vals.ConvertAll(e => (decimal)e);

Console.WriteLine($"Source type: {vals[0].GetType()}");
Console.WriteLine($"Result type: {res[0].GetType()}");
Console.WriteLine($"Converted values: {string.Join(", ", res)}");

The program creates a list of integers and uses ConvertAll with a lambda expression to cast each integer to a decimal. The resulting list contains decimal values, preserving the original numeric values but in a new type.

The GetType method confirms the type change from System.Int32 to System.Decimal. The converted values are printed to verify the transformation. This example is ideal for scenarios requiring type conversion, such as financial calculations needing decimal precision.

$ dotnet run
Source type: System.Int32
Result type: System.Decimal
Converted values: 1, 2, 3, 4, 5

Converting Words to Their Lengths

This example converts a list of strings into a list of their lengths, demonstrating how ConvertAll can derive new values from elements.

Program.cs
List<string> words = ["sky", "kanoe", "cannon", "war", "falcon"];
var lengths = words.ConvertAll(e => e.Length);

Console.WriteLine($"Words: {string.Join(", ", words)}");
Console.WriteLine($"Lengths: {string.Join(", ", lengths)}");

A list of words is defined, and ConvertAll applies a lambda expression that invokes the Length property of each string. The result is a new list containing the length of each word, assuming ASCII characters for simplicity.

The original list remains unchanged, and the new list of integers is printed alongside the source list. This example is useful for data analysis tasks, such as calculating text metrics or preparing data for further processing.

$ dotnet run
Words: sky, kanoe, cannon, war, falcon
Lengths: 3, 5, 6, 3, 6

Rounding Double Values

This example uses ConvertAll to round a list of double values to one decimal place, illustrating a transformation that modifies element values.

Program.cs
List<double> vals = [1.33, 2.27, 3.16, 4.93, 5.44];
var rounded = vals.ConvertAll(e => Math.Round(e, 1,
    MidpointRounding.AwayFromZero));

Console.WriteLine($"Original: {string.Join(", ", vals)}");
Console.WriteLine($"Rounded: {string.Join(", ", rounded)}");

The program defines a list of double values and uses ConvertAll with a lambda expression that applies Math.Round to round each value to one decimal place, using MidpointRounding.AwayFromZero for consistent rounding behavior.

The original and rounded lists are printed to show the transformation. This example is applicable in scenarios like formatting numerical data for display or standardizing measurements in scientific applications.

$ dotnet run
Original: 1.33, 2.27, 3.16, 4.93, 5.44
Rounded: 1.3, 2.3, 3.2, 4.9, 5.4

Converting Strings to Uppercase

This example converts a list of strings to their uppercase equivalents, demonstrating a transformation that modifies string content.

Program.cs
List<double> vals = [1.33, 2.27, 3.16, 4.93, 5.44];
var rounded = vals.ConvertAll(e => Math.Round(e, 1,
    MidpointRounding.AwayFromZero));

Console.WriteLine($"Original: {string.Join(", ", vals)}");
Console.WriteLine($"Rounded: {string.Join(", ", rounded)}");

A list of fruit names is transformed using ConvertAll with a lambda expression that applies the ToUpper method to each string. The result is a new list with all strings in uppercase, leaving the original list unchanged.

This example is useful for text processing tasks, such as normalizing data for case-insensitive comparisons or formatting text for display. The output shows both the original and transformed lists for comparison.

$ dotnet run
Original: apple, banana, cherry, date
Uppercase: APPLE, BANANA, CHERRY, DATE

Converting Objects to Strings

This example converts a list of custom objects to meaningful string representations, showing how ConvertAll can work with complex types and transform data.

Program.cs
var people = new List<Person>
{
    new("Alice", 25),
    new("Bob", 30),
    new("Charlie", 35)
};

var descriptions = people.ConvertAll(p => $"{p.Name} is {p.Age} years old.");

Console.WriteLine("People:");
foreach (var person in people) 
{
    Console.WriteLine($"  Name: {person.Name}, Age: {person.Age}");
}

Console.WriteLine("Descriptions:");
foreach (var desc in descriptions) 
{
    Console.WriteLine($"  {desc}");
}

record Person(string Name, int Age);

In this example, a list of Person records, each with Name and Age properties, is transformed into a list of strings using ConvertAll. The lambda expression generates a custom string for each person in the format "Name is Age years old."

This example is useful for generating human-readable output, such as creating reports, displaying user-friendly messages, or logging relevant details. The output highlights both the original objects and their transformed representations, showcasing the versatility of the ConvertAll method.

$ dotnet run
People:
  Name: Alice, Age: 25
  Name: Bob, Age: 30
  Name: Charlie, Age: 35
Descriptions:
  Alice is 25 years old.
  Bob is 30 years old.
  Charlie is 35 years old.

Source

List ConvertAll method

In this article, we explored how to convert list elements in C# using the ConvertAll method.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all C# tutorials.