I want to convert a List
to a List
.
Here is my code:
void Convert(List stringList)
{
With Linq:
var intList = stringList.Select(x => int.Parse(x)).ToList();
I would suggest using TryParse()
, in case some of the values are not convertible into int
.
For this I have created an Extension Method. Below is my demo LinqPad code.
void Main()
{
List<string> sourceList = new List<string> {"1", "2","3", "qwert","4", "5","6", "7","asdf", "9","100", "22"};
//Dump is a LinqPad only method. Please ignore
sourceList.ConvertToInt().Dump();
}
static public class HelperMethods
{
static public List<int> ConvertToInt(this List<string> stringList)
{
int x = 0;
var intList = stringList.Where(str => int.TryParse(str, out x))
.Select (str => x)
.ToList();
return intList;
}
}
In this case, only the numeric int values get parsed and the rest is gracefully ignored. You could built in some error handling / notification if you want to.
/Edit Based on Peter Kiss' suggestion here is a more generic approach based on the IEnumerable interface.
static public IEnumerable<int> ConvertToInt(this IEnumerable<string> source)
{
int x = 0;
var result = source.Where(str => int.TryParse(str, out x))
.Select (str => x);
return result;
}
With this you'd just have to call AsEnumerable()
before calling ConvertToInt()
The result is of course of type IEnumerable<Int32>
and from here on, you can convert it easily into a List by using .ToList()
or an array or whatever you need at that point.