Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most elegant way to load a string array into a List<int>?

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?

like image 593
bobbyalex Avatar asked Sep 30 '13 06:09

bobbyalex


4 Answers

You can use Enumerable.Select method

List<int> intList = intArray.Select(str => int.Parse(str)).ToList();
like image 54
Dmitrii Dovgopolyi Avatar answered Oct 21 '22 06:10

Dmitrii Dovgopolyi


(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();
like image 18
Display Name Avatar answered Oct 21 '22 08:10

Display Name


Just call Select():

using System.Linq;

var list = intArray.Select(x => Convert.ToInt32(x));

PS: Your question changed after I initially answered.

like image 3
Simon Whitehead Avatar answered Oct 21 '22 07:10

Simon Whitehead


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));
like image 2
Thilina H Avatar answered Oct 21 '22 08:10

Thilina H