Array ConvertAll action
In this chapter you will learn:
- Convert all elements from one type to another type
- Convert all string elements from lower case to upper case
- Convert an array of floats to an array of integers
Convert all array elements
using System;/* j a v a 2 s .com*/
public class MainClass
{
public static void Main()
{
string[] strArray = new string[] { "75.3", "25.999", "105.25" };
double[] doubleArray = Array.ConvertAll<string, double>(strArray, Convert.ToDouble);
Console.Write("Converted to doubles: ");
Array.ForEach<double>(doubleArray, delegate(double x) { Console.Write(x + " "); });
Console.WriteLine();
}
}
The code above generates the following result.
Change string case with ConvertAll
The following code changes string case for a string array.
using System;/*from j a v a 2 s . c om*/
public class MainClass
{
public static void Main()
{
string[] strArray2 = new string[] { "Blah", "Foo", "java2s.com" };
Console.Write("Before converting to-upper: ");
Array.ForEach<string>(strArray2, delegate(string x) { Console.Write(x + " "); });
Console.WriteLine();
string[] revArray = Array.ConvertAll<string, string>(strArray2, delegate(string s) { return s.ToUpper(); });
Console.Write("Converted to upper-case: ");
Array.ForEach<string>(revArray, delegate(string x) { Console.Write(x + " "); });
Console.WriteLine();
}
}
Convert float type element to int
using System;//from j a va2 s .c o m
using System.Collections;
class Sample
{
public static void Main()
{
float[] reals = { 1.3f, 1.5f, 1.8f };
int[] wholes = Array.ConvertAll(reals, r => Convert.ToInt32(r));
Array.ForEach(wholes, Console.WriteLine);
}
}
The output:
Next chapter...
What you will learn in the next chapter:
- How to filter array with delegate
- How to filter array with anonymous method
- Find with lambda expression
Home » C# Tutorial » Array