如何在C#中将int数组转换为long数组 [英] how to convert from int array to long array in C#

查看:172
本文介绍了如何在C#中将int数组转换为long数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个int数组,现在我将它转换成长类型。



那我该怎么办?

可以帮助我请。

谢谢。

I have a int Array and now I wnat convert it to long type.

So How must I do?
could help me please.
thanks.

推荐答案

在.NET framework 2.0版中,Microsoft将一个名为ConvertAll的泛型方法添加到Array类中。此方法允许将整个数组从一种数据类型转换为另一种数据类型。该方法创建一个新数组,循环遍历现有数组并为每个元素执行委托。委托的结果值存储在新数组中,该数组成为方法的返回值。



ConvertAll方法的语法如下:



result = Array.ConvertAll< input-type,output-type>(输入数组,转换器);

语法中的四个可更改元素是:



-input-type。输入数组中保存的项目类型。

-output-type。要在返回的数组中创建的项的类型。

-input-array。要复制和转换的数组。这必须是一个零维的数组。

-converter。包含用于转换数组中每个项的代码的委托。这可能像强制转换操作一样简单,也可能要复杂得多,可能会将每个数值转换为等效的英文文本作为字符串。委托必须接受输入数据类型的参数并返回输出数据类型的结果。





In the .NET framework version 2.0, Microsoft added a generic method named ConvertAll to the Array class. This method allows an entire array to be converted from one data type to another. The method creates a new array, loops through the existing array and executes a delegate for each element. The resultant value from the delegate is stored in the new array, which becomes the method's return value.

The syntax for the ConvertAll method is as follows:

result = Array.ConvertAll<input-type, output-type>(input-array, converter);
The four changeable elements in the syntax are:

-input-type. The type of the items held in the input array.
-output-type. The type of the items to be created in the returned array.
-input-array. The array to duplicate and convert. This must be a one-dimensional, zero-based array.
-converter. A delegate containing the code to use to convert each of the items in the array. This may be as simple as a cast operation or be much more complicated, perhaps converting each numeric value to its English text equivalent as a string. The delegate must accept a parameter of the input data type and return a result of the output data type.


int[] integerArray = new int[] { 1, 2, 3, 4, 5 };

long[] longArray = Array.ConvertAll<int, long>(integerArray,
    delegate(int i)
    {
        return (long)i;
    });


查看Array.ConvertAll,我相信会这样做。
Check out Array.ConvertAll, I believe that will do it.


类似于Orcun的回答,但使用lambda。 (.NET 3.5或更高版本)

Similar to Orcun's answer but uses a lambda. (.NET 3.5 or higher)
int[] a = { 2, 4, 6, 8, 10 };
long[] b = Array.ConvertAll(a, val => (long)val);



请注意,这是一个完整的副本数组,所以在某些情况下它可能效率不高。


Please note that this makes an entire copy of the array and so it might not be efficient in some cases.


这篇关于如何在C#中将int数组转换为long数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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