2010-06-21 193 views
11

将c#中int数组[1,2,3]中的字符串数组[[1,2,3]]转换为最快的方法?将字符串[]转换为int []

谢谢

+2

是肯定的项目仅在字符串格式的整数? – 2010-06-21 09:43:10

+0

是的,只有整数 – 2010-06-21 09:43:55

+0

查看http://stackoverflow.com/questions/1297231/convert-string-to-int-in-one-string-of-code-using-linq – abatishchev 2010-06-21 09:49:32

回答

13
var values = new string[] { "1", "2", "3" }; 
values.Select(x => Int32.Parse(x)).ToArray(); 
+1

Int32.TryParse是更快的Int32.Parse – 2010-06-21 10:00:10

+1

而这实际上并没有给一个数组......并且不是填充这样一个数组的“最快”(问题)方式。但除此之外...... – 2010-06-21 10:02:51

+1

a)它返回的数据结构与您要求的不同,b)Marc Gravell的答案比其他人在这里的答案要好一个数量级? – 2010-06-21 10:02:59

1

迭代和转换。

1

的比较是我知道有没有快速的方式,但你可以用一个“短的路“:

var numbers = new[] {"1", "2", "3"}; 

var result = numbers.Select(s => int.Parse(s)); 
int[] resultAsArray = result.ToArray(); 

如果你使用PLINK,你可以并行计算值。

22
string[] arr1 = {"1","2","3"}; 
int[] arr2 = Array.ConvertAll(arr1, s => int.Parse(s)); 

采用Array.ConvertAll确保(不同于LINQ Select/ToArray),该阵列是在合适大小初始化。你可以尽可能获得遮阳更快的展开,但并不多:

int[] arr2 = new int[arr1.Length]; 
for(int i = 0 ; i < arr1.Length ; i++) { 
    arr2[i] = int.Parse(arr[i]); 
} 

如果你需要的东西更快还是(或许是大容量文件/数据处理),然后写自己的解析可以帮助;内置的处理很多的边缘情况 - 如果你的数据更简单,你真的可以减少这一点。


另一种可选择的解析器的例子:

public static unsafe int ParseBasicInt32(string s) 
    { 
     int len = s == null ? 0 : s.Length; 
     switch(s.Length) 
     { 
      case 0: 
       throw new ArgumentException("s"); 
      case 1: 
       { 
        char c0 = s[0]; 
        if (c0 < '0' || c0 > '9') throw new ArgumentException("s"); 
        return c0 - '0'; 
       } 
      case 2: 
       { 
        char c0 = s[0], c1 = s[1]; 
        if (c0 < '0' || c0 > '9' || c1 < '0' || c1 > '9') throw new ArgumentException("s"); 
        return ((c0 - '0') * 10) + (c1 - '0'); 
       } 
      default: 
       fixed(char* chars = s) 
       { 
        int value = 0; 
        for(int i = 0; i < len ; i++) 
        { 
         char c = chars[i]; 
         if (c < '0' || c > '9') throw new ArgumentException("s"); 
         value = (value * 10) + (c - '0'); 
        } 
        return value; 
       } 
     } 
    } 
+1

关于ConvertAll的有趣点,不知道! – 2010-06-21 09:53:19

2

我可能会做的事:

string[] array = new[] { "1", "2" }; // etc. 
int[] ints = array.Select(x => int.Parse(x)).ToArray(); 

如果我能保证数据将只有整数。

如果不是:

string[] array = new[] { "1", "2" }; // etc. 
List<int> temp = new List<int>(); 
foreach (string item in array) 
{ 
    int parsed; 
    if (!int.TryParse(item, out parsed)) 
    { 
     continue; 
    } 

    temp.Add(parsed); 
} 

int[] ints = temp.ToArray(); 
1
string[] arr = new string[]{ "1", "2", "3" }; 
int[] lss = (from xx in arr 
      select Convert.ToInt32(xx)).ToArray();