Generics C#

Convert the Type of the Elements of a List

This C# program demonstrates how to convert all of the elements of a list of elements to a new type.

Program.cs

using System;
using System.Collections.Generic;


namespace XoaX {

    class Program {

        static public int ConvertToLength(string sString) {
            return sString.Length;
        }

        static void Main(string[] args) {
            string[] saCardinalVirtues = new string[] {
               "Prudence",
               "Justice",
               "Fortitude",
               "Temperance"
           };
            List<string> qCardinalVirtues = new List<string>(saCardinalVirtues);

            Console.WriteLine("Cardinal Virtues:");
            Console.WriteLine("-----------------");
            foreach (string sVirtue in qCardinalVirtues) {
                Console.WriteLine(sVirtue);
            }
            Console.WriteLine("");

            // Perform the conversion and get a converted list back
            List<int> qVirtueLengths = qCardinalVirtues.ConvertAll(new
            	Converter<string, int>(ConvertToLength));

            Console.WriteLine("Cardinal Virtue Lengths:");
            Console.WriteLine("------------------------");
            foreach (int iLength in qVirtueLengths) {
                Console.WriteLine(iLength);
            }
            Console.WriteLine("");
        }
    }

}
 

Output

Cardinal Virtues:
-----------------
Prudence
Justice
Fortitude
Temperance

Cardinal Virtue Lengths:
------------------------
8
7
9
10

Press any key to continue . . .
 
 

© 2007–2024 XoaX.net LLC. All rights reserved.