正确使用ConverAll是什么?它将一种类型转换为另一种类型吗?
What is the proper use of ConverAll ? Will it convert one type to another type?
喜欢
List<int> intList = new List<int>(); intList.Add(10); intList.Add(20); intList.Add(30); intList.Add(33); var query= intList.ConvertAll(x=>(double)x);为此,我可以使用cast或OfType<>.
for this i can use cast or OfType<>.
推荐答案ConvertAll 不是扩展方法,它是List<T>本身的真实方法.
它返回一个包含转换后元素的新列表.因此,在您的示例中,query变量实际上不是查询,而是List<double>.
It returns a new list containing the converted elements. So in your example, the query variable isn't actually a query, it's a List<double>.
Cast 和 OfType are 扩展方法,它们在IEnumerable上运行并返回IEnumerable<T>.但是,它们不适合您指定的用途:Cast可以转换引用类型,但不能转换值类型,仅将其取消装箱. OfType不执行任何转换,它仅返回已具有指定类型的所有元素.
Cast and OfType are extension methods that operate on IEnumerable and return an IEnumerable<T>. However they're not suitable for your stated purpose: Cast can convert reference types but cannot convert value types, only unbox them. OfType doesn't perform any conversion, it just returns any elements that are already of the specified type.
更多推荐
扩展方法ConvertAll
发布评论