C# convert string array to integer (or something other kind of data type) array

Many times in coding you are dealing with transforming data from one type to another.  I often find myself creating integers, longs, etc from strings.  Especially in .net for some reason.  I got tired of writing tons of code to handle this.  .Net gives you a great way to convert an array from one type to another.

Currently I would always end up writing a for loop iterating through the array and doing a manual copy.  It would look something like this:

string[] someStringValues;

int[] someIntValues = new int[someStringValues.Length];

for( int i = 0; i < someStringValues.Length; i++ )
{
   someIntValues[i] = int.Parse( someIntValues[i] );
}

Not horrible code, but there is a more succinct way of doing it!

string[] someStringValues;

int[] someIntValues = Array.ConvertAll<string, int>( someStringValues, int.Parse );


We have now moved all that code into 1 line.  With some more magic we can also move this into a generic templated solution and you could theoretically change any array type into another type with the appropriate converter.  This could apply not only to basic data types but complex classes with an associated converter.

Comments

Shahana said…
I am sure, many people will be helpful with your post.

Popular Posts