List ConvertAll
In this chapter you will learn:
Convert all elements in List
How to convert List element?
using System;//from jav a 2s . co 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);
}
}
ConvertAll with custom function
The following code uses custom function to do the conversion.
using System;/*ja v a2 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);
}
}
}
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » List