string to int[] - Ernst Kuschke

   Ernst Kuschke

     Arbitrary thoughts and musings on life, the universe and everything else

Syndication

News

    ernst kuschke (v1.0)

    My Photos

    Microsoft Most Valuable Professional

    Member in good standing

    View Ernst Kuschke's profile on LinkedIn

    Add to Technorati Favorites

Blogs I read

Books I recommend

General Links

string to int[]
There's been a cool (I found it interesting) discussion on converting a comma-delimited string of int values into an int array lately. Gregory posted the details here.

The discussion carried forth to declare an inline method, instead of delegating to intToString, which seemed even more elegant: (the method was now only one line!)


int i[] = Array.ConvertAll<string, int>(commadelimitedInts.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries), new Converter<string, int>(delegate(string inVal) {
return int.Parse(inVal); } ));

There's in fact a better, more elegant way to do this than my inline method (thanks to colleague Piers!):

int i[] = Array.ConvertAll<string, int>(commadelimitedInts.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries), new Converter<string, int>(System.
Convert.ToInt32));

Why not use the methods provided by the framework? :-)
Published Wednesday, May 31, 2006 8:06 PM by Ernst Kuschke
Filed under: ,

Comments

# re: string to int[]@ Wednesday, May 31, 2006 9:44 PM

slick :)

# re: string to int[]@ Thursday, June 01, 2006 1:24 AM

There is an even shorter way to do it:

       public int [] Parse(string line)
       {
         string[] parts = line.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
         return Array.ConvertAll<string, int>(parts,int.Parse);
       }
You do not need to create the delagte instance. The compiler will do it for you. If do not need the input arguments of the delegate you can even omit the declaration of input variables:

Array.ConvertAll<string, int>(parts, delegate { return 1; });


Yours,
 Alois Kraus
(Not yet MVP ;-)) )

# re: string to int[]@ Tuesday, July 29, 2008 10:40 PM

Alois, your tip is really cool

by b2b

# re: string to int[]@ Monday, October 20, 2008 12:51 PM

What's the best way to do the opposite?

int[] to comma delimitered string?

by Emil

# re: string to int[]@ Sunday, April 05, 2009 4:04 PM

Thanks a lot..

It's working fine....

by Partha

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: