List ConvertAll

In this chapter you will learn:

  1. How to convert all element in List
  2. ConvertAll with custom function

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:

  1. How to find elements in List with your own condition