Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

.net - Difference between Select and ConvertAll in C#

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...