0

Possible Duplicate:
Parse string to int array

I have string which comes from a numeric textbox like this: 2670053157. how should I split each character of string and insert them into List<int> elements?

0

5 Answers 5

6
var list = numberString.Select(c => Int32.Parse(c.ToString())).ToList();

Or, if you'd rather add to an existing list:

list.AddRange(numberString.Select(c => Int32.Parse(c.ToString()));
Sign up to request clarification or add additional context in comments.

Comments

5
var list = new List<int>();

list.AddRange(
    from character in numericString
    select int.Parse(character));

Comments

5
 List<int> numericlist = "2670053157".Select(c => c - '0').ToList();

5 Comments

What did you do there? c - '0'
@Silvermind - Chars are ints. Subracting '0' (48) from '2' (50) would result in 2.
The only reason I wouldn't suggest doing it this way is because it won't properly handle the case where there is a non-numeric character in the string.
@JustinNiessner Thanks, Learned some new logic today.
@JustinNiessner it would be good in cases where exception is not wanted (Int.Parse would throw exception and Int.TryParse does not suit well to linq)
1

If you're afraid of exceptions being thrown due to improper inputs, you could always go the safe route:

// string input = TextBox1.Text;
List<int> intList = new List<int>();

foreach (char c in input)
{
    int i;
    if (Int32.TryParse(c.ToString(), out i))
    {
        intList.Add(i);
    }
}

Comments

1

Start out with a helper method:

public static IEnumerable<short> getDigits(long input)
{
    while (input > 0)
    {
        yield return (short)(input % 10);
        input /= 10;
    }
}

Then if you want the values in a list, just call ToList:

List<short> list = getDigits(2670053157).ToList();

If you want the higher order bits first you'll need to Reverse the sequence:

List<short> list = getDigits(2670053157).Reverse().ToList();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.