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.




About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 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.

Unknown said...

A+1