Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string[] To Decimal[],int[],float[] .double[] in c#

Tags:

c#

silverlight

string[] txt1 = new string[]{"12","13"};

this.SetValue(txt1, v => Convert.ChangeType(v, typeof(decimal[]), null));

it throws an error - Object must implement IConvertible.

I also want a code to convert string[] To Decimal[],int[],float[] .double[]

like image 988
Malcolm Avatar asked Feb 12 '26 16:02

Malcolm


1 Answers

You can't convert a string[] straight to a decimal[] like that - all the elements have to be individually converted to the new type. Instead, you can use Array.ConvertAll

string[] txt1 = new string[]{"12","13"};
decimal[] dec1 = Array.ConvertAll<string, decimal>(txt1, Convert.ToDecimal);

And similarly using Convert.ToInt32, Convert.ToSingle, Convert.ToDouble for the Converter<TInput,TOutput> argument to produce int[], float[], double[], substituting in the correct type arguments to ConvertAll

EDIT: As you're using silverlight, which doesn't have ConvertAll, you'll have to do it manually:

decimal[] dec1 = new decimal[txt1.Length];
for (int i=0; i<txt1.Length; i++) {
    dec1[i] = Convert.ToDecimal(txt1[i]);
}
like image 51
thecoop Avatar answered Feb 15 '26 10:02

thecoop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!