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.

Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

6 comments:

Anonymous said...

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

Well done...

Suprotim Agarwal said...

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

Anonymous said...

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

- Penning

Anonymous said...

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());

Jason Carney said...

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.

Ashfaque Hussain said...

A+1