I'm getting integeres to my controller as 123456 in one variable.
Now I want to transform each number to separated from other with comma between as array of numbers as { 1, 2, 3, 4, 5 }
.
I'm getting integeres to my controller as 123456 in one variable.
Now I want to transform each number to separated from other with comma between as array of numbers as { 1, 2, 3, 4, 5 }
.
Try this
var integers = "123456";
var enumOfInts = integers.ToCharArray().Select(x => Char.GetNumericValue(x));
try this:
int[] array = new int["123456".ToArray().Count()];
int i = 0;
foreach (var item in "123456".ToArray())
{
array[i++] = int.Parse(item.ToString());
}
or
int[] array = "123456".ToArray().Select(data=>(int)data).ToArray();
{
string s = "1234567890";
var lst = new List<int>();
for (int n = 0; n < s.Length; n++)
{
int x;
if (int.TryParse(s[n].ToString(), out x))
lst.Add(x);
}
int[] arr = lst.ToArray();
}
If you are getting parameter as string then
The Linq Way :
string str_num = "123456"
var arrayOfInts = str_num.ToCharArray().Select(x => x - 48).ToArray();
for the above Linq expression it has been assumed that all character are between 48
& 57
Non Linq Way :
int[] GetIntArray(string str_num)
{
int num = Int32.Parse(str_num);
List<int> listOfInts = new List<int>();
while(num > 0)
{
listOfInts.Add(num % 10);
num = num / 10;
}
listOfInts.Reverse();
return listOfInts.ToArray();
}
Solution extended from : How to split a number into individual digits in c#?