Jump to content

C# Converting String Array to Int Array

Fyfey96

Hello,

I have this line of code.

DataValues_int = DataValues_raw.Select(s => int.Parse(s)).ToArray();

but I am getting "Exception thrown: 'System.OverflowException' in mscorlib.dll"

 

The raw array has text in it. Which are actually numbers. So i want them to convert to ints so i can work with them. Im sure i had this working before lol.

 

Thanks, 

Alistair

Link to comment
Share on other sites

Link to post
Share on other sites

for(int i = 0; i < DataValues_Raw.Length; i++){
	DataValues_Int[i] = Int32.Parse(DataValues_Raw[i]);
}

Assuming both arrays are the same size of course, and that the DataValues_Raw has numbers ONLY.

Quote or tag if you want me to answer! PM me if you are in a real hurry!

Why do Java developers wear glasses? Because they can't C#!

 

My Machines:

The Gaming Rig:

Spoiler

-Processor: i5 6600k @4.6GHz

-Graphics: GTX1060 6GB G1 Gaming

-RAM: 2x8GB HyperX DDR4 2133MHz

-Motherboard: Asus Z170-A

-Cooler: Corsair H100i

-PSU: EVGA 650W 80+bronze

-AOC 1080p ultrawide

My good old laptop:

Spoiler

Lenovo T430

-Processor: i7 3520M

-4GB DDR3 1600MHz

-Graphics: intel iGPU :(

-Not even 1080p

 

Link to comment
Share on other sites

Link to post
Share on other sites

1 hour ago, Fyfey96 said:

Hello,

I have this line of code.


DataValues_int = DataValues_raw.Select(s => int.Parse(s)).ToArray();

but I am getting "Exception thrown: 'System.OverflowException' in mscorlib.dll"

 

The raw array has text in it. Which are actually numbers. So i want them to convert to ints so i can work with them. Im sure i had this working before lol.

 

Thanks, 

Alistair

That code works when all the data is valid. You're getting an overflow exception because at least one of your string values are too large to be converted to an int.

 

For example

int.Parse("212324124124124124"); // throws an OverflowException
long.Parse("212324124124124124"); // works

Either you need to make sure that DataValues_raw doesn't contain any invalid data, or you need to modify your code to properly handle invalid data.

Link to comment
Share on other sites

Link to post
Share on other sites

2 hours ago, dany_boy said:

for(int i = 0; i < DataValues_Raw.Length; i++){
	DataValues_Int[i] = Int32.Parse(DataValues_Raw[i]);
}

Assuming both arrays are the same size of course, and that the DataValues_Raw has numbers ONLY.

 

1 hour ago, madknight3 said:

That code works when all the data is valid. You're getting an overflow exception because at least one of your string values are too large to be converted to an int.

 

For example


int.Parse("212324124124124124"); // throws an OverflowException
long.Parse("212324124124124124"); // works

Either you need to make sure that DataValues_raw doesn't contain any invalid data, or you need to modify your code to properly handle invalid data.

Brilliant. I'll these tomorrow when I'm back at work. 

 

Thanks for the help :) 

Link to comment
Share on other sites

Link to post
Share on other sites

String[] DataValues_Raw = {"2342345", "83762829", "7216189", "87271902"}; //just some random numbers, replace this initializtion with your values
            int[] DataValues_Int; //Declare the numeric array
            //whatever code in between declaration and usage of your 2 variables
            DataValues_Int = new int[DataValues_Raw.Length]; //this line ensures the target array is the same length as the original one
            
            for (int i = 0; i < DataValues_Raw.Length; i++) //The loop repeats itself as many times as there are elements from the original array
            {
                DataValues_Int[i] = Int32.Parse(DataValues_Raw[i]); //Here is the code that parses the string into numbers
            }

            foreach (int number in DataValues_Int)//this loop is just to show the results
            {
                Console.WriteLine("numer {0} + 1", number);     //print the numbers as text
                Console.WriteLine(number + 1);                  //do some arithmetics with the array to show that they are actually integers
            }

That is a very simple example showing you how it works. If you need extra bits for your numbers, you can use long or even ulong instead of int. Just take in mind ulong can't be negative values.

Cheers!

Quote or tag if you want me to answer! PM me if you are in a real hurry!

Why do Java developers wear glasses? Because they can't C#!

 

My Machines:

The Gaming Rig:

Spoiler

-Processor: i5 6600k @4.6GHz

-Graphics: GTX1060 6GB G1 Gaming

-RAM: 2x8GB HyperX DDR4 2133MHz

-Motherboard: Asus Z170-A

-Cooler: Corsair H100i

-PSU: EVGA 650W 80+bronze

-AOC 1080p ultrawide

My good old laptop:

Spoiler

Lenovo T430

-Processor: i7 3520M

-4GB DDR3 1600MHz

-Graphics: intel iGPU :(

-Not even 1080p

 

Link to comment
Share on other sites

Link to post
Share on other sites

public static class EnumExt
{

	public IEnumerable<T> ConvertTo<S,T>(this IEnumerable<S> seq, Func<S,T> conv)
    {
      	foreach(var itm in seq)
      	{
      		yeild return conv(itm);
      	}
    }

}

Define that class of extention methods somewhere.

 

Then for your array of strings (called myStrArry)

myStrArry.ConvertTo( x => Int32.Parse(x) ).ToArray();

To summarize, create an extention method for converting any enumerable of type S to an enumerable of type T by providing a conversion function (in this case a lambda)...then use it.


Edit:  Totally forgot about the extension method Select() in LINQ...

Link to comment
Share on other sites

Link to post
Share on other sites

Still getting the error could this be because there is quotes in the text.. ie around the numbers? 

 

Cheers

Screenshot.jpg

Link to comment
Share on other sites

Link to post
Share on other sites

5 hours ago, Fyfey96 said:

Still getting the error could this be because there is quotes in the text.. ie around the numbers? 

 

Cheers

Screenshot.jpg

Yes, the parse function will only recognize numerical characters (numbers, points and minus). Make sure your XML file reads like this: value="4227072" and not like this value=\"4227072\". The backslash before a symbol denotes a special character. Cheers!

Quote or tag if you want me to answer! PM me if you are in a real hurry!

Why do Java developers wear glasses? Because they can't C#!

 

My Machines:

The Gaming Rig:

Spoiler

-Processor: i5 6600k @4.6GHz

-Graphics: GTX1060 6GB G1 Gaming

-RAM: 2x8GB HyperX DDR4 2133MHz

-Motherboard: Asus Z170-A

-Cooler: Corsair H100i

-PSU: EVGA 650W 80+bronze

-AOC 1080p ultrawide

My good old laptop:

Spoiler

Lenovo T430

-Processor: i7 3520M

-4GB DDR3 1600MHz

-Graphics: intel iGPU :(

-Not even 1080p

 

Link to comment
Share on other sites

Link to post
Share on other sites

If you cannot modify the XML file, then you can also use the Split() function from the String class like so:

	String[] DataValues_Raw = { "\"2342345\"", "\"8376282\"", "\"7216189\"", "\"87271902\"" }; //just some random numbers, replace this initializtion with your values
    int[] DataValues_Int; //Declare the numeric array
    //whatever code in between declaration and usage of your 2 variables
    DataValues_Int = new int[DataValues_Raw.Length]; //this line ensures the target array is the same length as the original one
            
    for (int i = 0; i < DataValues_Raw.Length; i++) //The loop repeats itself as many times as there are elements from the original array
    {
        DataValues_Int[i] = Int32.Parse(DataValues_Raw[i].Split('\"')[1]); //Here is the code that parses the string into numbers
    }

    foreach (string text in DataValues_Raw)
        Console.WriteLine("This is the raw text: {0}", text);

    foreach (int number in DataValues_Int)//this loop is just to show the results
    {
        Console.Write("This is the number {0}, and here is the number + 1: ", number);
        Console.WriteLine(number + 1);                  //do some arithmetics with the array to show that they are actually integers
    }       

 

Quote or tag if you want me to answer! PM me if you are in a real hurry!

Why do Java developers wear glasses? Because they can't C#!

 

My Machines:

The Gaming Rig:

Spoiler

-Processor: i5 6600k @4.6GHz

-Graphics: GTX1060 6GB G1 Gaming

-RAM: 2x8GB HyperX DDR4 2133MHz

-Motherboard: Asus Z170-A

-Cooler: Corsair H100i

-PSU: EVGA 650W 80+bronze

-AOC 1080p ultrawide

My good old laptop:

Spoiler

Lenovo T430

-Processor: i7 3520M

-4GB DDR3 1600MHz

-Graphics: intel iGPU :(

-Not even 1080p

 

Link to comment
Share on other sites

Link to post
Share on other sites

If your planning to use a fixed format that is invalid then just pre-process it prior to converting to make it valid string list.

for(int i = 0; i < DataValues_Raw.Length; i++){
	var ProcessedString = DataValues_Raw[i].Replace("\"", string.Empty);
	DataValues_Int[i] = Int32.Parse(ProcessedString);
}

I also suggest adding some checking mechanism using All or TryParse to stop any troublesome string that make through.

numberList
.Select(str => str.Replace("\"", string.Empty))				//formats your strings
.Where(str => str.All(char.IsDigit)					//takes only strings with digits
.Select(str => int.Parse(str))						//convert to ints
.ToList()

Hope everything works :$

Link to comment
Share on other sites

Link to post
Share on other sites

35 minutes ago, P4ZD4 said:

If your planning to use a fixed format that is invalid then just pre-process it prior to converting to make it valid string list.


for(int i = 0; i < DataValues_Raw.Length; i++){
	var ProcessedString = DataValues_Raw[i].Replace("\"", string.Empty);
	DataValues_Int[i] = Int32.Parse(ProcessedString);
}

I also suggest adding some checking mechanism using All or TryParse to stop any troublesome string that make through.


numberList
.Select(str => str.Replace("\"", string.Empty))				//formats your strings
.Where(str => str.All(char.IsDigit)					//takes only strings with digits
.Select(str => int.Parse(str))						//convert to ints
.ToList()

Hope everything works :$

I am now using a console application and this is now working...?

 

<code> Data_Values_Int = Data_Values_Raw.Select(x => int.Parse(x)).ToArray(); </code>

Link to comment
Share on other sites

Link to post
Share on other sites

On 1/24/2017 at 1:41 PM, Fyfey96 said:

Still getting the error could this be because there is quotes in the text.. ie around the numbers? 

 

Cheers

Screenshot.jpg

 

Oops sorry didn't see this post clearly, never mind about the quotes that's how the debugger represents string values.

 

So now its working in a console app? :| What type and size is DataValues_int array? Try using TryParse and see if it returns a true value on each number maybe you can pinpoint when the error is occurring.

Link to comment
Share on other sites

Link to post
Share on other sites

9 hours ago, P4ZD4 said:

 

Oops sorry didn't see this post clearly, never mind about the quotes that's how the debugger represents string values.

 

So now its working in a console app? :| What type and size is DataValues_int array? Try using TryParse and see if it returns a true value on each number maybe you can pinpoint when the error is occurring.

I have decided to go with a console app now anyway. Dint really need a forms app anyway. DataValues_int is the same length as DataValues_raw except int array is ints and raw array is strings.

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×