What I would like to learn how to do is to convert an int array to an int in C#.
However I want to append the int with the values from the array.
Example:
int[] array = {5, 6, 2, 4};
Would be converted into an int that equals 5624.
Thanks for any help in advance.
You can convert a String to integer using the parseInt() method of the Integer class. To convert a string array to an integer array, convert each element of it to integer and populate the integer array with them.
Apache Commons Lang's ArrayUtils class provides toPrimitive() method that can convert an Integer array to primitive ints.
simply multiply each number with 10^ his place in the array.
int[] array = { 5, 6, 2, 4 };
int finalScore = 0;
for (int i = 0; i < array.Length; i++)
{
finalScore += array[i] * Convert.ToInt32(Math.Pow(10, array.Length-i-1));
}
int output = array
.Select((t, i) => t * Convert.ToInt32(Math.Pow(10, array.Length - i - 1)))
.Sum();
Another simple way:
int[] array = {5, 6, 2, 4};
int num;
if (Int32.TryParse(string.Join("", array), out num))
{
//success - handle the number
}
else
{
//failed - too many digits in the array
}
Trick here is making the array a string of digits then parsing it as integer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With