locked
Converting Array Type in C#

    Question

  • Lets say I have an method that returns an Array of strings. I want to convert the array of strings to array of integers. How would I do that in C#?

    string[] values = {"1","2","3"};

    int[] intValues;

     

    I want to cast "values" to "intValues". What would be the syntax?

     

    Thanks,

    Rajesh

    Wednesday, May 16, 2007 6:52 PM

Answers

  • And the Linq way (available in Orcas)

     

                string[] strings = new[] { "1", "2", "3", "4" };

                int[] ints = strings.Select(x => int.Parse(x)).ToArray();

    Marcelo.

    Thursday, May 17, 2007 10:34 PM
  • Try something like this

     

    string[] array = {"1", "2", "3"};

    int[] values = new int[array.Length];

    for(int x = 0; x < array.Length; x++)

    {

       values[x] = Convert.ToInt32(array[x].ToString());

    }

     

    Nathan

    Wednesday, May 16, 2007 7:44 PM
  • You can't cast, if that's what you're looking for.  You'll have to convert each element, one by one.  For example:

    Code Snippet

    string[] strings = {"1", "2", "3"};

    int[] numbers = new int[strings.Length];

    int i = 0;

    foreach(String text in strings)

    {
      int.TryParse(text, out numbers[i]);
      ++i;

    }

    foreach(int number in numbers)

    {

     Console.WriteLine(number);

    }

     


     

    Wednesday, May 16, 2007 7:49 PM

All replies

  • Try something like this

     

    string[] array = {"1", "2", "3"};

    int[] values = new int[array.Length];

    for(int x = 0; x < array.Length; x++)

    {

       values[x] = Convert.ToInt32(array[x].ToString());

    }

     

    Nathan

    Wednesday, May 16, 2007 7:44 PM
  • Code Snippet

    string[] values = {"1","2","3"};

    int[] intValues = new int[values.Length];

    for (int i=0;i < values.Length;i++)

    {

    intValues[i] = Convert.ToInt32(values[i]);

    }

     

    Nathan beat me to it. :-)
    Wednesday, May 16, 2007 7:47 PM
  • You can't cast, if that's what you're looking for.  You'll have to convert each element, one by one.  For example:

    Code Snippet

    string[] strings = {"1", "2", "3"};

    int[] numbers = new int[strings.Length];

    int i = 0;

    foreach(String text in strings)

    {
      int.TryParse(text, out numbers[i]);
      ++i;

    }

    foreach(int number in numbers)

    {

     Console.WriteLine(number);

    }

     


     

    Wednesday, May 16, 2007 7:49 PM
  • Code Snippet

    int[] numbers = Array.ConvertAll<string, int>(strings, delegate(string str) { return int.Parse(str); } );



    But as already mentionned, this wel generate an exception if there is a string that can't be parsed... So TryParse might be a better option if you want to keep the values that where actually valid...
    Thursday, May 17, 2007 8:14 AM
  • And the Linq way (available in Orcas)

     

                string[] strings = new[] { "1", "2", "3", "4" };

                int[] ints = strings.Select(x => int.Parse(x)).ToArray();

    Marcelo.

    Thursday, May 17, 2007 10:34 PM
  • when i put this "think" ...(x=> int.Parse(x))... (sorry for my Engilsh) in the For loop,
     and when I build it in second iteration program stops working and i see warning (or whatever): "Input string was not in a correct format."
    Would you explain me what I can do with it, plz
    Thursday, October 08, 2009 8:25 PM
  • You dont have to put this in a for loop.
    x=>int.Parse(x).ToArray will convert all the elements of string array to int......

    Hope this helps........:)
    Wednesday, November 18, 2009 11:50 PM
  • thx, that helped me a lot.
    Friday, November 20, 2009 7:54 PM
  • And the Linq way (available in Orcas)

     

                string[] strings = new[] { "1", "2", "3", "4" };

                int[] ints = strings.Select(x => int.Parse(x)).ToArray();

    Marcelo.



    Hi guys and thank you dear Marcelo Guerra.

    Your answer was exactly correct, but I had another question and I wish that you (or another person in Microsoft support group) give me the best solution.

    What can I do when type of second array is unkown?!

    I wanna convert a typed array to another parametrized typed array. For example, if I had a array of string type, then I'll give a type as a parameter (ex. typeof(int)) and I've to convert my typed array (first) to given type.

    Something like below function... I don't know what's the best method to convert given array to a result of that array with given type.

    Regards.

    from Antonom
    Microsoft Certified Technology Specialist (MCTS)
    Microsoft Certified Professional (MCP)
    Phone: +989124227902, +989375141781

    public IList ConvertArray(string[] firstArray, Type targetType)

    {

              […]

    }

    Monday, January 17, 2011 4:29 PM
  • You can use Convert.ChangeType.

        static public IList ConvertArray(string[] firstArray, Type targetType)
        {
          Array array = Array.CreateInstance(targetType, firstArray.Length);
          for (int i = 0; i < firstArray.Length; i++)
          {
            array.SetValue(Convert.ChangeType(firstArray[i], targetType), i);
          }
          return array;
        }
    

     

    Monday, January 17, 2011 5:55 PM
  • You can use Convert.ChangeType.

     static public IList ConvertArray(string[] firstArray, Type targetType)
    
     {
    
      Array array = Array.CreateInstance(targetType, firstArray.Length);
    
      for (int i = 0; i < firstArray.Length; i++)
    
      {
    
      array.SetValue(Convert.ChangeType(firstArray[i], targetType), i);
    
      }
    
      return array;
    
     }
    
    

     


    Dear Louis.fr

    Hi.

    Although, your solution was correct and I agree with you in this way, but I'm not sure about the constructor of array types. I've found the same as this solution and I'm looking for another trusted way. (without using Convert and reflection resources). There're many exceptions for converting customized types with Convert.ChangeType. Also if I have a array with a parameterless constructor, this code will going to be crashed. Anyway, I'd like to be the best. ;)

    I should thank you.

    "Best wishes"

    from Antonom
    Microsoft Certified Technology Specialist (MCTS)
    Microsoft Certified Professional (MCP)
    Phone: +989124227902, +989375141781

    Tuesday, January 18, 2011 12:43 PM
  • 1) What is "a array with a parameterless constructor"?

    2) There is no universal way to convert between types, except to Object. The closer to universal conversion is to string, but the default ToString method returns only the type name.

    Tuesday, January 18, 2011 2:31 PM
  •  

    As first:

     

    public class FixedArray

            : ArrayList

    {

            public FixedArray()

                    : base(100)

            { }

     

            public override bool IsFixedSize

            {

                    get

                    {

                            return true;

                    }

            }

    }

     

    That’s a fixed size array with a parameterless constructor. ;). You cann't pass this class through CreateInstance(typeof(FixedArray), fixedArray.Length).

    As second:

    “Dear Louis.fr”

    I wanna do something like a complex way of serialization and dependency property structure in WPF.

    I’ve to convert every property value to string and convert it back,,,

    Got it?

    Thank you.


    Antonom
    Tuesday, January 18, 2011 3:24 PM
  • 1) This is not an array. Hence my question about "array constructors".

    2) Isn't there already ways to serialize objects?

    3) You shouldn't propose your own replies as answer. Specially when it's not answering the OP.

    Tuesday, January 18, 2011 5:51 PM
  • 1) This is not an array. Hence my question about "array constructors".

    2) Isn't there already ways to serialize objects?

    3) You shouldn't propose your own replies as answer. Specially when it's not answering the OP.


    Deal Louis.fr:

    a. It's a customized array type. what I mean of array is array definition, it's not just brackets!

    b. Maybe yes, but in performance issues and output I've many big problems in xml serialization.

    c. I'm so sorry. I'm new in here and if You have any instruction of using this CP, I'll hope to give it to me.

    'Thank you.'


    Antonom
    Wednesday, January 19, 2011 6:47 AM
  • An array is a class inheriting from the Array class. No more, no less.

    An ArrayList is not an array: it's a list using an array as internal storage. That's why the "Array" part of the name comes first.

    Wednesday, January 19, 2011 11:13 AM
  • Ping Moderator:

    could you split this post into two? Once containing the original (and answered) question, and a second one where Antonom invaded?

    Many thanks

    RK


    "The improbable we do, the impossible just takes a little longer." (Steven Parker)
    Wednesday, January 19, 2011 11:30 AM
  • var values = {"1","2","3"};
    var ints = values.Select(int.Parse).ToArray();
    

    Thursday, September 22, 2011 9:42 PM
  • string[] splitter = new string[] { "," };
    string []reps = pv.VISIT_TEST.Split(splitter, StringSplitOptions.RemoveEmptyEntries);
    Array.Sort(reps);
    
           List<int> general = new List<int>();
           List<int> specific = new List<int>();
    
                    foreach (string s in reps)
                    {
                        int i;
                        if (int.TryParse(s.Trim(), out i))
                        {
                            if (i != 3 && i != 5 && i != 6 && i != 7 && i != 8)
                            {
                                general.Add(i);
                            }
                            else
                            {
                                specific.Add(i);
                            }
                        }
                    }
    try this one..........



    • Edited by Afzal_gujrat Saturday, November 05, 2011 8:22 PM
    • Proposed as answer by Afzal_gujrat Saturday, November 05, 2011 8:22 PM
    Saturday, November 05, 2011 8:21 PM
  • Thanks Marcelo this worked out for me.

    Vishwa

    Monday, December 19, 2011 9:03 PM