C# List ConvertAll
last modified July 5, 2023
In this article we show how to convert list elements into another type in C#
using the ConvertAll
method.
C# list is a collection of elements of the same type. The elements can be accessed by index.
public List<TOutput> ConvertAll<TOutput> (Converter<T,TOutput> converter);
TOutput
is the type of the elements of the target list.
Converter
is a delegate that converts each element from one type to
another type.
The method returns a list of the target type containing the converted elements from the source list. The elements of the source list are not modified.
C# List convert ints to decimals
In the next example, we use ConvertAll
to convert a list of
integers into a list of decimals.
var vals = new List<int> { 1, 2, 3, 4, 5 }; List<decimal> res = vals.ConvertAll((e) => (decimal)e); Console.WriteLine(vals[0].GetType()); Console.WriteLine(res[0].GetType());
We define a list of integers. From the list we generate a new list where the source elements are converted into decimals.
List<decimal> res = vals.ConvertAll((e) => (decimal)e);
We pass the ConvertAll
method a lambda expression, where we cast
the integer values into decimals.
Console.WriteLine(vals[0].GetType()); Console.WriteLine(res[0].GetType());
With GetType
, we determine the type of the first element of the
source and target lists.
$ dotnet run System.Int32 System.Decimal
C# list convert words to word lengths
In the next example, we use the ConvertAll
method to convert a list
of strings into a list of string lengths.
var words = new List<string> { "sky", "kanoe", "cannon", "war", "falcon"}; var wlens = words.ConvertAll((e) => e.Length); Console.WriteLine(string.Join(",", words)); Console.WriteLine(string.Join(",", wlens));
We assume that we work only with ASCII characters.
var words = new List<string> { "sky", "kanoe", "cannon", "war", "falcon"};
We have a list of words.
var wlens = words.ConvertAll((e) => e.Length);
The converter is a lambda expression which invokes the Length
property on each list element.
$ dotnet run sky,kanoe,cannon,war,falcon 3,5,6,3,6
C# list rounding elements
In the next example, we round the elements of a list.
var vals = new List<double> { 1.33, 2.27, 3.16, 4.93, 5.44 }; var res = vals.ConvertAll((e) => double.Round(e, 1, MidpointRounding.AwayFromZero)); Console.WriteLine(string.Join(",", vals)); Console.WriteLine(string.Join(",", res));
We define a list of double values. The values are rounded.
var res = vals.ConvertAll((e) => double.Round(e, 1, MidpointRounding.AwayFromZero));
For rounding, we use the MidpointRounding.AwayFromZero
mode.
$ dotnet run 1.33,2.27,3.16,4.93,5.44 1.3,2.3,3.2,4.9,5.4
Source
In this article we have showed how to convert list elements in C# with
ConvertAll
.
Author
List all C# tutorials.