c# - How to convert List<string> to List<int>?

ID : 20059

viewed : 12

Tags : c#c#

Top 5 Answer for c# - How to convert List<string> to List<int>?

vote vote

95

listofIDs.Select(int.Parse).ToList() 
vote vote

83

Using Linq ...

List<string> listofIDs = collection.AllKeys.ToList();   List<int> myStringList = listofIDs.Select(s => int.Parse(s)).ToList(); 
vote vote

79

Here is a safe variant that filters out invalid ints:

List<int> ints = strings     .Select(s => Int32.TryParse(s, out int n) ? n : (int?)null)     .Where(n => n.HasValue)     .Select(n => n.Value)     .ToList(); 

It uses an out variable introduced with C#7.0.

This other variant returns a list of nullable ints where null entries are inserted for invalid ints (i.e. it preserves the original list count):

List<int?> nullableInts = strings     .Select(s => Int32.TryParse(s, out int n) ? n : (int?)null)     .ToList(); 
vote vote

65

What no TryParse? Safe LINQ version that filters out invalid ints (for C# 6.0 and below):

List<int>  ints = strings     .Select(s => { int i; return int.TryParse(s, out i) ? i : (int?)null; })     .Where(i => i.HasValue)     .Select(i => i.Value)     .ToList(); 

credit to Olivier Jacot-Descombes for the idea and the C# 7.0 version.

vote vote

57

Using Linq:

var intList = stringList.Select(s => Convert.ToInt32(s)).ToList() 

Top 3 video Explaining c# - How to convert List<string> to List<int>?

Related QUESTION?