Array ConvertAll action

In this chapter you will learn:

  1. Convert all elements from one type to another type
  2. Convert all string elements from lower case to upper case
  3. 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:

  1. How to filter array with delegate
  2. How to filter array with anonymous method
  3. Find with lambda expression
Home » C# Tutorial » Array
Array
Array loop
Array dimension
Jagged Array
Array length
Array Index
Array rank
Array foreach loop
Array ForEach Action
Array lowerbound and upperbound
Array Sort
Array search with IndexOf methods
Array binary search
Array copy
Array clone
Array reverse
Array ConvertAll action
Array Find
Array SequenceEqual