I read a list of numbers from a text document and saved them in a List<String> and I am trying to convert those numbers into a List<int>. The numbers are separated by spaces. Here is what I tried, assuming Numbers is the String list:
List<int> AllNumbers = Numbers.ConvertAll<int>(Convert.ToInt32);
When I try to use this is says “Input string was not in a correct format.”
What is the correct way to convert a List<String> into a List<int>?
SAMPLE:
string numbers = File.ReadAllText("numbers.txt");
string[] allNumbers = numbers.Split(new char[] { ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
List<string> List = new List<string>();
List.AddRange(allNumbers);
I then want to take the List allNumbers and convert it to a List of integers.
The text file looks like this:
10 12 01 03 22….ect
It looks like your numbers are in a single string separated by spaces if so you can use Linq:
If you really have a
List<string>numbers already simply:Or finally, if each string may contain multiple numbers separated by spaces: