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

我从一个表单中接收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);
}

当前回答

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

其他回答

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

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

没有TryParse吗? 安全的LINQ版本,过滤掉无效的int(适用于c# 6.0及以下):

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

这要归功于Olivier Jacot-Descombes的想法和c# 7.0版本。

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

你可以通过LINQ使用它

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

我知道这是一个老帖子,但我认为这是一个很好的补充: 您可以使用List<T>。ConvertAll < TOutput >

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