Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this the best way in C# to convert a delimited string to an int array?

Tags:

string

c#

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();
    }
}
like image 933
Soni Ali Avatar asked Apr 28 '09 12:04

Soni Ali


2 Answers

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));
}
like image 73
Marc Gravell Avatar answered Sep 19 '22 14:09

Marc Gravell


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();
like image 34
Richard Ev Avatar answered Sep 19 '22 14:09

Richard Ev