jpavlov
jpavlov

Reputation: 2261

Trouble converting string into List<int>

I have a string that looks like "34,45,74,23" and is dynamically generated. How do I convert this into a List?

var y = numString();
y.ToList();

Upvotes: 0

Views: 80

Answers (4)

Selman Genç
Selman Genç

Reputation: 101681

This should give you a List<int>.

str.Split(',').Select(int.Parse).ToList();

If you are not sure that all strings are parsable to int, or your string contains multiple commas like 23,,24,25 or invalid charachters you can use Where to filter the sequence first:

var numbers = str.Split(',').Where(x => x.All(char.IsDigit)).Select(int.Parse);

Or you can use TryParse:

var numbers = str.Split(',').Select(x =>
        {
            int result;
            if (int.TryParse(x, out result)) return result;
            return int.MinValue;
        }).Where(x => x != int.MinValue).ToList();

Probably, TryParse is the best option because char.IsDigit returns true for all digits, not just (0-9).

Upvotes: 5

Tim Schmelter
Tim Schmelter

Reputation: 460138

If you are sure that the format is valid you can use Array.ConvertAll and the List<T> constructor which is more efficient:

string[] numbers = "34,45,74,23".Split(',');
var list = new List<int>(Array.ConvertAll(numbers, int.Parse));

Upvotes: 1

Sean
Sean

Reputation: 62472

Using Linq:

var numbers = y.Split(',').Select(num => int.Parse(num)).ToList();

Upvotes: 2

Yaakov Ellis
Yaakov Ellis

Reputation: 41500

This should do it for you

string source = "34,45,74,23";
var stringArray = source.Split(',');
var intArray = stringArray.Select(x => Convert.ToInt32(x)).ToList();

Upvotes: 1

Related Questions