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

我从一个表单中接收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语句。推荐的答案在。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);
}

其他回答

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

使用Linq…

List<string> listofIDs = collection.AllKeys.ToList();  
List<int> myStringList = listofIDs.Select(s => int.Parse(s)).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版本。

对于这个简单的问题来说,这可能有点过头了。但是对于与Linq连接的Try-Do方法,我倾向于使用匿名类来实现更有表现力的代码。这与Olivier Jacot-Descombes和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();

使用Linq:

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