How to convert a String[] to int[] in C# and .NET 2.0?

前端 未结 6 1909
名媛妹妹
名媛妹妹 2020-12-15 04:37

I\'ve got :

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

And I want something like this

int[] intArray = Con         


        
相关标签:
6条回答
  • 2020-12-15 05:21
    int[] intArray = Array.ConvertAll(strArray, int.Parse);
    

    or in C# 2.0 (where the generic type inference is weaker):

    int[] intArray = Array.ConvertAll<string,int>(strArray, int.Parse);
    
    0 讨论(0)
  • 2020-12-15 05:22

    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); });
    

    (EDIT: 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.)

    Using a for-loop:

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

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

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

    or:

    //EDIT: Probably faster since a fixed-size buffer is used
    var intArray = Array.ConvertAll(strArray, int.Parse);
    
    0 讨论(0)
  • 2020-12-15 05:23

    When you are sure, all items are definitely parsable, this will do the trick:

    string[] strArray = new string[3] { "1", "2", "12" };
    int[] intArray = new int[strArray.Length];
    for (int i = 0; i < strArray.Length; i++)
    {
        intArray[i] = int.Parse(strArray[i]);
    }
    
    0 讨论(0)
  • 2020-12-15 05:29

    Something like this, but you want to keep a bit of error checking ( my if is really lame, just as example ):

    static private int[] toIntArray(string[] strArray)
    {
        int[] intArray = new int[strArray.Length];
        for (int index = 0; index < strArray.Length; index++)
        {
                intArray[index] = Int32.Parse(strArray[index]);
        }
        return intArray;
    }
    

    And use it like this:

    string[] strArray = new string[3] { "1", "2", "12" };
    int[] interi = toIntArray(strArray);
    
    0 讨论(0)
  • 2020-12-15 05:38
    using System.Collections.Generic;
    
    int Convert(string s)
    {
        return Int32.Parse(s);
    }
    
    int[] result = Array.ConvertAll(input, new Converter<string, int>(Convert));
    

    or

    int[] result = Array.ConvertAll(input, delegate(string s) { return Int32.Parse(s); })
    
    0 讨论(0)
  • 2020-12-15 05:39

    Array.ConvertAll Generic Method

    Converts an array of one type to an array of another type.

    0 讨论(0)
提交回复
热议问题