tags:

views:

1000

answers:

3

I have some List:

List<int> list = new List<int> { 1, 2, 3, 4, 5 };

I want to apply some transformation to elements of my list. I can do this in two ways:

List<int> list1 = list.Select(x => 2 * x).ToList();
List<int> list2 = list.ConvertAll(x => 2 * x).ToList();

What is the difference between these two ways?

+7  A: 

ConvertAll is not an extension, it's a method in the list class. You don't have to call ToList on the result as it's already a list:

List<int> list2 = list.ConvertAll(x => 2 * x);

So, the difference is that the ConvertAll method only can be used on a list, and it returns a list. Select can be used on any ienumerable collection, and it returns an ienumerable.

Guffa
+13  A: 

Select is a LINQ extension method and works on all IEnumerable<> objects whereas ConvertAll is implemented only by List<>. The ConvertAll method exists since .NET 2.0 whereas LINQ was introduced with 3.5.

You should favor Select over ConvertAll as it works for any kind of list, but they do the same basically.

Oliver Hanappi
A: 

Select and ConvertAll have been covered already.

Alternatively, you can consider using ForEach, which does some action on each element in-place. When you use objects, this is perhaps preferred. ForEach is a a method of List<>.

List<someObject> list;
list.ForEach(x => x.DoSomething());

UPDATE: removed incorrect statements

Abel
Select is not there to return a subset of the elements (this would be Where). Select performs a transformation on each element and returns the transformed element.
Oliver Hanappi
You can't use Select to get a subset of the list. That is done with the Where method.
Guffa
you are both correct. I'll remove that bit of my answer
Abel