Try this:
string str = "1,2,3,4";
int[] array = str.Split(',').Select(x => int.Parse(x)).ToArray();
If there's a chance that you might have a string with double commas (ex: 1,,2,3,4
) then this will work better as per @Callum Linington's comment:
int[] array = str.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
What the code above does it:
- Create an array of strings after the call to
Split()
so after that method call we'll have something like this: { "1", "2", "3", "4"}
- Then we pass each one these strings to
int.Parse()
which will convert them to 32-bit signed integers.
- We take all these integers and make an array out of them with
ToArray()
.