Consider an array of strings containing numerical values:
string[] intArray = {"25", "65" , "0"};
What is the most elegant way to load the numbers into a List<int>
without using a for
or while
to iterate over the intArray
?
You can use Enumerable.Select method
List<int> intList = intArray.Select(str => int.Parse(str)).ToList();
(addition to Dmitry's answer)
You can get rid of lambda, because that method already has the right signature:
List<int> intList = intArray.Select(Int32.Parse).ToList();
Just call Select()
:
using System.Linq;
var list = intArray.Select(x => Convert.ToInt32(x));
PS: Your question changed after I initially answered.
This is the way to do it..
string[] intArray = { "25", "65", "0" };
List<int> intList = new List<int>(Array.ConvertAll(intArray, s => int.Parse(s)));
OR
string[] intArray = { "25", "65", "0" };
List<int> intList = new List<int>(intArray.Select(int.Parse).ToArray());
OR
string[] intArray = { "25", "65", "0" };
List<int> intList = new List<int>(Array.ConvertAll(intArray, int.Parse));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With