CSharpFeeds - All your C# feeds in one place.

Sponsors

Wednesday, October 04, 2006

List.ConvertAll<>()

by Keyvan Nayyeri via Keyvan Nayyeri on 10/4/2006 2:33:00 PM

Notice the usage of List<T>.ConvertAll() method in my previous post:

public String Points

{

    get

    {

        return String.Join(" | ",

            (String[])this.myStudent.Points.ConvertAll

            (new Converter<Double, String>(delegate(Double value)

            {

                return Convert.ToString(value);

            }

            )).ToArray());

    }

}

Who has said we should write a simple code?!!  I used List<T>.ConvertAll() function to get a List<String> from a List<Double> then converted my List<String> to an Array of Strings.

List<T>.ConvertAll() method is a new .NET 2.0 Generic method which gets a System.Converter object and converts each element in a List<T> from type T to the outgoing type.  It seems this method is using a predicate but actually it doesn't do this.

ConvertAll() method gets a Converter object which converts each item from incoming type to outgoing type.  Converter gets a delegate as its parameters.  This logic for this delegate must convert an incoming value of first type to the second type and return it.  In above example I used anonymous method to save my time.

For better understanding of this method you can take a look at following Console Application example.  I used simpler code and divided my code to more steps to let you know what's going on.

static void Main(string[] args)

{

    // Set Initial Data

    List<Double> numbers = new List<Double>();

    for (int i = 0; i < 10; i++)

        numbers.Add(i + 0.25);   

 

    // Define a Converter

    Converter<Double, String> converter =

        new Converter<Double, String>(delegate(Double value)

    {

        return Convert.ToString(value);

    });

 

    String[] strNumbers;

 

    // Convert a List<String> to Array of Strings

    strNumbers = (String[])numbers.ConvertAll(converter).ToArray();

 

    // Show the Output           

    Console.WriteLine(String.Join(" ", strNumbers));

 

    Console.ReadLine();

}

First a List<Double> is created then using a Converter this List<Double> is converted to List<String> and finally List<String> is converted to Array of Strings and has been sent to output.

email it!bookmark it!digg it!

Original Post: List.ConvertAll<>()

Subscribe

New Feed

Product Spotlight

Recently Updated Sources

Legal Note

The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.

Advertise with us