List<T>.ConvertAll<>() with Lambda Expression

List<T> has many useful methods for dealing with sequences and collections. One such method is the ConvertAll<>() method. All those who have used the List<T>.ConvertAll<>() are aware how useful this method is to convert the current List<T> elements to another type, and return a list of converted elements. However, an instance of a conversion delegate must be passed to this method, which knows how to convert each instance from the source type to the destination type.

For eg: Convert a List<int> to List<string>

ConvertAll with Delegate

However combined with a Lamda Expression, this method can be used to write terse code.

Here’s an example. Let us say we want to rewrite the same code shown above which converts a List<int> to List<string> in the shortest possible way

ConvertAll with Lambda

Add a breakpoint, debug the code and you will see that ConvertAll<>() converted the List<int> to List<string>.

ConvertAll with Lambda

Note: Since ConvertAll() creates a new collection, sometimes this may be inefficient.

6 comments:

  1. This looks amazingly similar to http://stackoverflow.com/questions/44942/cast-listint-to-liststring

    Well done...

    ReplyDelete
  2. Yes quite similar. This is a standard example to demonstrate ConvertAll with Lambda. Thanks for the link!

    ReplyDelete
  3. thanks for this example. I used it to solve an int to decimal conversion

    - Penning

    ReplyDelete
  4. Um... you can do this just as easily with Select.

    List ints = new List() { 1, 2, 3, 4, 5 };

    IEnumerable strings = ints.Select(i => i.ToString());

    ReplyDelete
  5. The difference between Select and Convertall is Select is a LINQ extension method on IEnumerable and ConvertAll is just a List method present since .Net 2.5. I prefer Select.

    ReplyDelete