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);
}
Solution 1:
listofIDs.Select(int.Parse).ToList()
Solution 2:
Using Linq ...
List<string> listofIDs = collection.AllKeys.ToList();
List<int> myStringList = listofIDs.Select(s => int.Parse(s)).ToList();
Solution 3:
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();
Solution 4:
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.
Solution 5:
Using Linq:
var intList = stringList.Select(s => Convert.ToInt32(s)).ToList()