Menus

Tuesday, December 4, 2012

List.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.

No comments:

Post a Comment