views:

499

answers:

4

Given the string below:

string str = "1,2,3";

Will this be the best extension to convert it to an int array?

static class StringExtensions
{
    public static int[] ToIntArray(this string s)
    {
        return ToIntArray(s, ',');
    }
    public static int[] ToIntArray(this string s, char separator)
    {
        string[] ar = s.Split(separator);
        List<int> ints = new List<int>();
        foreach (var item in ar)
        {
            int v;
            if (int.TryParse(item, out v))
                ints.Add(v);
        }
        return ints.ToArray();
    }
}
+2  A: 

This approach is very terse, and will throw a (not very informative) FormatException if the split string contains any values that can't be parsed as an int:

int[] ints = str.Split(',').Select(s => int.Parse(s)).ToArray();

If you just want to silently drop any non-int values you could try this:

private static int? AsNullableInt(string s)
{
    int? asNullableInt = null;

    int asInt;

    if (int.TryParse(s, out asInt))
    {
        asNullableInt = asInt;
    }

    return asNullableInt;
}

// Example usage...
int[] ints = str.Split(',')
    .Select(s => AsNullableInt(s))
    .Where(s => s.HasValue)
    .Select(s => s.Value)
    .ToArray();
Richard Ev
+12  A: 

It really depends what you want to do with the non-integer strings. At the moment you silently drop them. Personally, I'd want it to error. This also lets you use the more terse:

public static int[] ToIntArray(this string value, char separator)
{
    return Array.ConvertAll(value.Split(separator), s=>int.Parse(s));
}
Marc Gravell
I think you need to undo Sasha's edit.
Erich Mirabal
@Erich - thanks.
Marc Gravell
A: 

It looks OK, I would also throw an exception if one of the items could not be converted instead of silently failing.

Otávio Décio
+2  A: 

This will blow up if one of your elements in the list does not parse as int, which is probably better than silently failing:

public static int[] ToIntArray(this string value, char separator)
{
    return value.Split(separator).Select(i => int.Parse(i)).ToArray();
}
Winston Smith