Difference between Select and ConvertAll in C#

前端 未结 4 1121
遇见更好的自我
遇见更好的自我 2020-12-01 04:50

I have some List:

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

I want to apply some transformation to elements of my list.

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 05:36

    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 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. The Select method can be used on any collection that implements the IEnumerable interface, and it returns an IEnumerable.

    Also, they do the processing differently, so they have their strengths in different situations. The ConvertAll method runs through the list and creates a new list in one go, while the Select method uses lazy execution and only processes the items as you need them. If you don't need all the item, the Select method is more efficient. On the other hand, once ConvertAll has returned the list, you don't need to keep the original list.

提交回复
热议问题