Emerica.
Emerica.

Reputation: 568

Converting a List<String> to List<int>

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

Upvotes: 2

Views: 3883

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

Assuming that each string in the list contains one or more integer numbers separated by spaces, you can try this approach:

var res = listOfNumbers
    .SelectMany(numStr => numStr.Split(' ').Select(s => int.Parse(s)))
    .ToList();

You can use method group instead of lambda in the last select: Select(int.Parse)

Upvotes: 1

BrokenGlass
BrokenGlass

Reputation: 161002

It looks like your numbers are in a single string separated by spaces if so you can use Linq:

List<int> allNumbers = numbers.Split(' ').Select(int.Parse).ToList();

If you really have a List<string> numbers already simply:

List<int> allNumbers = numbers.Select(int.Parse).ToList();

Or finally, if each string may contain multiple numbers separated by spaces:

List<int> allNumbers  = numbers.SelectMany(x=> x.Split(' ')).Select(int.Parse).ToList();

Upvotes: 5

Related Questions