tags:

views:

149

answers:

4

I have a function (tointarray) to convert a string into an array of ints, but I am not very satisfied with it. it does the job but there must be a more elegant way to do this, perhaps Linq could help here. unfortunately I am not very good in Linq. do you guys know a better way? my function:

{
    string s1 = "1;2;3;4;5;6;7;8;9;10;11;12";
    int[] ia = tointarray(s1, ';');
}
int[] tointarray(string value, char sep)
{
    string[] sa = value.Split(sep);
    int[] ia = new int[sa.Length];
    for (int i = 0; i < ia.Length; ++i)
    {
        int j;
        string s = sa[i];
        if (int.TryParse(s, out j))
        {
            ia[i] = j;
        }                 
    }
    return ia;
}
+11  A: 
s1.Split(';').Select(s => Convert.ToInt32(s)).ToArray();

Untested and off the top of my head...testing now for correct syntax.

Tested and everything looks good.

Justin Niessner
Can't you just do: `s1.Split(';').Select(Convert.ToInt32).ToArray();`
strager
@strager - No, that statement doesn't compile.
Justin Niessner
@strager, apparently you cannot to that using .Net 4.0. You are dreaming in Python ;)
Hamish Grubijan
Nah, I've been spending too much time with Javascript. =]
strager
It usually does work, since the method name will be cast to the correct Func/predicate/delegate. The reason it doesn't work with Convert.ToInt32 is because of the Convert(string,int) overload that confuses the type inference. `s1.Split(';').Select((Func<string,int>)Convert.ToInt32).ToArray()` works correctly, but isn't really any less code
Mike
Anyway the given implementation isn't correct since unlike given sample it fail on inputs that contains non integer strings.
Jakub Šturc
@Jakub - Depending on how you truly want the code to function, this might be exactly what you're looking for. Not everybody wants arbitrary zeros in their results.
Justin Niessner
@Justin: Right, but I couldn't help myself.
Jakub Šturc
+4  A: 

This post asked a similar question and used LINQ to solve it, maybe it will help you out too.

static void Main(string[] args)
    {           
        string s1 = "1;2;3;4;5;6;7;8;9;10;11;12";
        int[] ia = s1.Split(';').Select(n => Convert.ToInt32(n)).ToArray();
    }
JSprang
thanks to @ll; JSprang you were as fast as justin; u need reps => i will accepts urs ;)
Oops
I would use int.Parse tho.
Femaref
@Femaref makes a good point! Thanks...
JSprang
+1  A: 

Here's code that filters out invalid fields:

    var ints = from field in s1.Split(';').Where((x) => { int dummy; return Int32.TryParse(x, out dummy); })
               select Int32.Parse(field);
David Gladfelter
+3  A: 

Actually correct one to one implementation is:

int n;
int[] ia = s1.Split(';').Select(s => int.TryParse(s, out n) ? n : 0).ToArray();
Jakub Šturc