将string []转换为int []

Luc*_*oli 11 c# arrays string integer

哪个是在c#中int的数组[1,2,3]中转换字符串数组["1","2","3"]的最快方法?

谢谢

Mar*_*ell 23

string[] arr1 = {"1","2","3"};
int[] arr2 = Array.ConvertAll(arr1, s => int.Parse(s));
Run Code Online (Sandbox Code Playgroud)

使用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]);
}
Run Code Online (Sandbox Code Playgroud)

如果你还需要更快的东西(也许是批量文件/数据处理),那么编写自己的解析可能会有所帮助; 内置的一个处理很多边缘情况 - 如果你的数据更简单,你真的可以减少一点.


有关替代解析器的示例:

    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;
                }
        }
    }
Run Code Online (Sandbox Code Playgroud)


Sly*_*Sly 13

var values = new string[] { "1", "2", "3" };
values.Select(x => Int32.Parse(x)).ToArray();
Run Code Online (Sandbox Code Playgroud)