EDIT: I hadn't spotted the ".NET 2.0" requirement. If you're going to do a lot of this sort of thing, it would probably be worth using LINQBridge, and see the later bit - particularly if you can use C# 3.0 while still targeting 2.0. Otherwise:
List<int> integers = new List<int>(text.Length);
foreach (char c in text)
{
integers.Add(c - '0');
}
Not as neat, but it will work. Alternatively:
List<char> chars = new List<char>(text);
List<int> integers = chars.ConvertAll(delegate(char c) { return c - '0'; });
Or if you'd be happy with an array:
char[] chars = text.ToCharArray();
int[] integers = Arrays.ConvertAll<char, int>(chars,
delegate(char c) { return c - '0'; });
Original answer
Some others have suggested using ToCharArray
. You don't need to do that - string already implements IEnumerable<char>
, so you can already treat it as a sequence of characters. You then just need to turn each character digit into the integer representation; the easiest way of doing that is to subtract the Unicode value for character '0':
IEnumerable<int> digits = text.Select(x => x - '0');
If you want this in a List<int>
instead, just do:
List<int> digits = text.Select(x => x - '0').ToList();