Linq: convert string to int array
Posted
by Oops
on Stack Overflow
See other posts from Stack Overflow
or by Oops
Published on 2010-06-02T15:32:06Z
Indexed on
2010/06/02
15:43 UTC
Read the original article
Hit count: 759
I have a function (tointarray) to convert a string into an array of ints, but I am not very satisfied with it. it does the job but there must be a more elegant way to do this, perhaps Linq could help here. unfortunately I am not very good in Linq. do you guys know a better way? my function:
{
string s1 = "1;2;3;4;5;6;7;8;9;10;11;12";
int[] ia = tointarray(s1, ';');
}
int[] tointarray(string value, char sep)
{
string[] sa = value.Split(sep);
int[] ia = new int[sa.Length];
for (int i = 0; i < ia.Length; ++i)
{
int j;
string s = sa[i];
if (int.TryParse(s, out j))
{
ia[i] = j;
}
}
return ia;
}
© Stack Overflow or respective owner