在C#中选择并ConvertAll的区别 [英] Difference between Select and ConvertAll in C#

查看:802
本文介绍了在C#中选择并ConvertAll的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些列表:

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?

推荐答案

选择是一个LINQ的扩展方法,并适用于所有的IEnumerable<>而ConvertAll的对象是通过列表与LT仅执行;>。该ConvertAll方法存在,因为.NET 2.0,而LINQ与3.5引入的。

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.

您应该偏向选择了ConvertAll,因为它适用于任何类型的列表,但他们做同样的基本上是这样。

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

这篇关于在C#中选择并ConvertAll的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆