Thursday, February 16, 2006
« Express Database Editions | Main | Cingular 2125 - Not »

Just came across this little generic gem:

string[] input = { "1", "2", "3", "4", "5", "6", "7", "8", "9" };

int[] output = Array.ConvertAll<string, int>(input, delegate(string s) { return int.Parse(s); });

 

I have a number of web.config files that store lists of integers as comma separated strings. This is a clean way to convert it all to an int array. (It is in need of some exception handling.)

 

<appSettings>

      <add key="MachineIDs" value="44,3,43,566" />

</appSettings>

 

private int[] GetConfigIntArray(string key)

{

    string[] values  = ConfigurationManager.AppSettings[key].Split(',');

    return Array.ConvertAll<string, int>(values, delegate(string s) { return int.Parse(s); });

}

kick it on DotNetKicks.com   Thursday, February 16, 2006 10:46:59 PM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [5]  | 
Thursday, March 02, 2006 8:43:19 AM (Pacific Standard Time, UTC-08:00)
Hi.
thats a nice way of doing it, but wouldn't it be possible using the IntCollection?

string[] myString {"1","2","3"};
int[] myInt = IntCollection.ConvertStringToIntArray(myString);

/J
Jonas
Thursday, March 02, 2006 8:48:28 AM (Pacific Standard Time, UTC-08:00)
Jonas,

I can't find ConvertStringToIntArray. Can you point me in the right direction?

Thanks,
Andrew Robinson
Friday, March 03, 2006 12:54:18 AM (Pacific Standard Time, UTC-08:00)
Hi.
Let me appologize!

The method i mentioned is not part of any of the standard .NET classes.

I had a look at what was in that class and compared it to the code you wrote, and i must say that your example is better.

I used it to take a comma delimietd string from a textbox and make an int array of the values.

Again, let me appologize for making this statement before i realized that the Intcollection wasn't part of the standard.

/J
Jonas
Friday, March 03, 2006 7:00:12 AM (Pacific Standard Time, UTC-08:00)
Jonas,

Not a big deal. I was just wondering what you were using.

There are many ways that you can convert an array of one type to another. Writing your own function is an option and there there are likely lots of peole out there doing this other ways.

The predicate function (anonymous delegate in my case) makes this elegant from a source code standpoint but I don't think it is any more efficiant that what could be coded with a traditional for loop using int.Parse().

-Andrew
Andrew Robinson
Friday, December 07, 2007 6:52:16 AM (Pacific Standard Time, UTC-08:00)
I think that this isn't a big deal (to master) but anyhow a must have (as technique).
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview