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 ConvertAll with Delegate](http://lh5.ggpht.com/-wbK4RNIFsGY/Tedp1Hd5jNI/AAAAAAAACA4/ZoqsgAw-lPM/image%25255B16%25255D.png?imgmax=800)
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 ConvertAll with Lambda](http://lh5.ggpht.com/-iQ-nsnb3ZLY/Tedp2SKgekI/AAAAAAAACA8/rK0AIth3oS0/image%25255B13%25255D.png?imgmax=800)
Add a breakpoint, debug the code and you will see that ConvertAll<>() converted the List<int> to List<string>.
![ConvertAll with Lambda ConvertAll with Lambda](http://lh3.ggpht.com/-1GOroinurT0/Tedp4Z7W9cI/AAAAAAAACBA/1LhnVhtptvo/image%25255B8%25255D.png?imgmax=800)
Note: Since ConvertAll() creates a new collection, sometimes this may be inefficient.
Tweet
6 comments:
This looks amazingly similar to http://stackoverflow.com/questions/44942/cast-listint-to-liststring
Well done...
Yes quite similar. This is a standard example to demonstrate ConvertAll with Lambda. Thanks for the link!
thanks for this example. I used it to solve an int to decimal conversion
- Penning
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());
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.
A+1
Post a Comment