I have a string that has numbers
string sNumbers = \"1,2,3,4,5\";
I can split it then convert it to List
var numbers = sNumbers.Split(',').Select(Int32.Parse).ToList();
You can also do it this way without the need of Linq:
List<int> numbers = new List<int>( Array.ConvertAll(sNumbers.Split(','), int.Parse) );
// Uses Linq
var numbers = Array.ConvertAll(sNumbers.Split(','), int.Parse).ToList();
Joze's way also need LINQ, ToList()
is in System.Linq
namespace.
You can convert Array to List without Linq by passing the array to List constructor:
List<int> numbers = new List<int>( Array.ConvertAll(sNumbers.Split(','), int.Parse) );
You can use this:
List<Int32> sNumberslst = sNumbers.Split(',').ConvertIntoIntList();
Better use int.TryParse
to avoid exceptions;
var numbers = sNumbers
.Split(',')
.Where(x => int.TryParse(x, out _))
.Select(int.Parse)
.ToList();
You can use new C# 6.0 Language Features:
(s) => { return Convert.ToInt32(s); }
with
corresponding method group Convert.ToInt32
new Converter<string, int>(Convert.ToInt32)
with: Convert.ToInt32
The result will be:
var intList = new List<int>(Array.ConvertAll(sNumbers.Split(','), Convert.ToInt32));