C# List ConvertAll
Description
List
converts
the elements in the current List
Syntax
public List<TOutput> ConvertAll<TOutput>(
Converter<T, TOutput> converter
)
Parameters
TOutput
- The type of the elements of the target array.converter
- A Converter delegate that converts each element from one type to another type.
Example
How to convert List element?
using System;/*from w ww . j a va 2s. c o m*/
using System.Collections;
using System.Collections.Generic;
class Sample
{
public static void Main()
{
//Create a List of Strings
//String-typed list
List<string> words = new List<string>();
words.Add("A");
words.Add("B");
words.Add("C");
words.Add("D");
words.Add("E");
words.Add("F");
List<string> upperCastWords = words.ConvertAll(s => s.ToUpper());
List<int> lengths = words.ConvertAll(s => s.Length);
}
}
Example 2
The following code uses custom function to do the conversion.
using System;// w w w .j a v a 2 s.c om
using System.Collections.Generic;
class ListConvertAll
{
static double TakeSquareRoot(int x)
{
return Math.Sqrt(x);
}
static void Main()
{
List<int> integers = new List<int>();
integers.Add(1);
integers.Add(2);
integers.Add(3);
integers.Add(4);
Converter<int, double> converter = TakeSquareRoot;
List<double> doubles = integers.ConvertAll<double>(converter);
foreach (double d in doubles)
{
Console.WriteLine(d);
}
}
}
The code above generates the following result.