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>
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
Add a breakpoint, debug the code and you will see that ConvertAll<>() converted the List<int> to List<string>.
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