如何转换一个String []到int []在C#和.NET 2.0吗? [英] How to convert a String[] to int[] in C# and .NET 2.0?

查看:102
本文介绍了如何转换一个String []到int []在C#和.NET 2.0吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有:

string[] strArray = new string[3] { "1", "2", "12" };

和我想是这样的。

int[] intArray = Convert.toIntArray(strArray);



我的工作INT C#.net 2.0,我不想写很多代码

I work int C# .net v2.0, I don't want to write a lot of code.

我怎么能这样做?

感谢您。

推荐答案

您可以使用 Array.ConvertAll 用于此目的,这法转换一种类型的数组为另一种类型的数组。

You can use the Array.ConvertAll method for this purpose, which "converts an array of one type to an array of another type."

int[] intArray = Array.ConvertAll(strArray,
                                  delegate(string s) { return int.Parse(s); });



(编辑:类型推断工作正常使用该技术或者,你也可以使用一个隐含的方法。 。-group转换为马克Gravell的答案,但你必须明确地指定泛型类型参数)

( Type-inference works fine with this technique. Alternatively, you could also use an implicit method-group conversion as in Marc Gravell's answer, but you would have to specify the generic type-arguments explicitly.)

使用for循环:

int[] intArray = new int[strArray.Length];

for (int i = 0; i < strArray.Length; i++)
   intArray[i] = int.Parse(strArray[i]);

有关完整性,在这样做的惯用方式C#4.0会是这样的:

For completeness, the idiomatic way of doing this in C# 4.0 would be something like:

var intArray = strArray.Select(int.Parse).ToArray();

//EDIT: Probably faster since a fixed-size buffer is used
var intArray = Array.ConvertAll(strArray, int.Parse);

这篇关于如何转换一个String []到int []在C#和.NET 2.0吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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