Search code examples
c#arrays

How to convert decimal array to string array in C#?


i need to convert Decimal array to string array . How to convert decimal[] to string[] ? Can i use

Array.ConvertAll()

method to do this task?


Solution

  • Of course you can use Array.ConvertAll method. You just need a conversation which can be done easyly with lambda expression.

    string[] string_array = Array.ConvertAll(decimal_array, x => x.ToString());
    

    Array.ConvertAll converts an entire array. It converts all elements in one array to another type.

    Let's code it;

    decimal[] decimal_array = new decimal[] {1.1M, 1.2M, 1.3M, 1.4M };
    string[] string_array = Array.ConvertAll(decimal_array, x => x.ToString());
    
    foreach (var item in string_array)
    {
          Console.WriteLine("{0} - {1}", item.GetType(), item);
    }
    

    Output will be;

    System.String - 1.1
    System.String - 1.2
    System.String - 1.3
    System.String - 1.4
    

    Here is a DEMO.