[c#] How to convert List<string> to List<int>?

My question is part of this problem:

I recieve a collection of id's from a form. I need to get the keys, convert them to integers and select the matching records from the DB.

[HttpPost]
public ActionResult Report(FormCollection collection)
{
    var listofIDs = collection.AllKeys.ToList();  
    // List<string> to List<int>
    List<Dinner> dinners = new List<Dinner>();
    dinners= repository.GetDinners(listofIDs);
    return View(dinners);
}

This question is related to c#

The answer is


Using Linq ...

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

I know it's old post, but I thought this is a good addition: You can use List<T>.ConvertAll<TOutput>

List<int> integers = strings.ConvertAll(s => Int32.Parse(s));

  public List<int> ConvertStringListToIntList(List<string> list) 
  {
     List<int> resultList = new List<int>();
     for (int i = 0; i < list.Count; i++)
        resultList.Add(Convert.ToInt32(list[i]));

     return resultList;
  }

Another way to accomplish this would be using a linq statement. The recomended answer did not work for me in .NetCore2.0. I was able to figure it out however and below would also work if you are using newer technology.

[HttpPost]
public ActionResult Report(FormCollection collection)
{
    var listofIDs = collection.ToList().Select(x => x.ToString());
    List<Dinner> dinners = new List<Dinner>();
    dinners = repository.GetDinners(listofIDs);
    return View(dinners);
}

This is the simplest way, I think:

var listOfStrings = (new [] { "4", "5", "6" }).ToList();
var listOfInts = listOfStrings.Select<string, int>(q => Convert.ToInt32(q));

This may be overkill for this simple problem. But for Try-Do methods in connection with Linq, I tend to use anonymous classes for more expressive code. It is similar to the answers from Olivier Jacot-Descombes and BA TabNabber:

List<int> ints = strings
    .Select(idString => new { ParseSuccessful = Int32.TryParse(idString, out var id), Value = id })
    .Where(id => id.ParseSuccessful)
    .Select(id => id.Value)
    .ToList();

Using Linq:

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

intList = Array.ConvertAll(stringList, int.Parse).ToList();

yourEnumList.Select(s => (int)s).ToList()

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.


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

You can use it via LINQ

     var selectedEditionIds = input.SelectedEditionIds.Split(",").ToArray()
                            .Where(i => !string.IsNullOrWhiteSpace(i) 
                             && int.TryParse(i,out int validNumber))
                            .Select(x=>int.Parse(x)).ToList();

Convert string value into integer list

var myString = "010"; 
int myInt;
List<int> B = myString.ToCharArray().Where(x => int.TryParse(x.ToString(), out myInt)).Select(x => int.Parse(x.ToString())).ToList();