How to convert List<string> to List<int>?

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

Using Linq ...

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

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();

Tags:

C#