Difference between Select and ConvertAll in C#

前端 未结 4 1109
遇见更好的自我
遇见更好的自我 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:30

    The first answer should not be the accepted one. I am a former 2007 C# Microsoft MVP.

    In contrast to the accepted response, ConvertAll is much more efficient than the combination of Select and ToList().

    First of all, ConvertAll is strictly faster and it uses the minimum amount of memory to do so. Same as Array.ConvertAll vs Select and ToArray. This would be a much more evident with a larger length array or many calls within a loop.

    1) ConvertAll knows the size of the final list and avoids reallocating the base array. ToList() will keep resizing the array multiple times.

    2) ToList will make slower interface IEnumerable<> calls, while ConvertAll will loop through the underlying array without extra calls or range checks.

    3) Select will create an extra IEnumerable<T> object.

    0 讨论(0)
  • 2020-12-01 05:33

    Select is a LINQ extension method and works on all IEnumerable<T> objects whereas ConvertAll is implemented only by List<T>. 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.

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

    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.

    0 讨论(0)
  • 2020-12-01 05:46

    I know this is bit late but i have still added because this could be of some use for others in future.

    When using it in EntityFramework query expression it is not recommended to use ConvertAll() as it evaluates the expression rather than leaving it as expression for future use. This seriously degrades database query execution performance as it would have to make number of calls before evaluating final expression.

    0 讨论(0)
提交回复
热议问题