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();
}
}
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));
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With