我的问题是这个问题的一部分:

我从一个表单中接收id的集合。我需要获取键,将它们转换为整数,并从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);
}

当前回答

使用Linq:

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

其他回答

另一种实现方法是使用linq语句。推荐的答案在。net core2.0中对我不起作用。然而,我能够弄清楚,如果你使用更新的技术,下面也可以工作。

[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);
}

下面是一个过滤无效整型的安全变体:

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

它使用c# 7.0引入的out变量。

另一个变量返回一个可为空的int列表,其中为无效的int插入null项(即它保留原始列表计数):

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

将字符串值转换为整数列表

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();
intList = Array.ConvertAll(stringList, int.Parse).ToList();
listofIDs.Select(int.Parse).ToList()