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

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

当前回答

没有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版本。

其他回答

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

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

使用Linq:

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

这将字符串数组转换为长数组。它返回成功转换的值的个数。

public static int strv_to_longv(string[] src, int src_offset, long[] dst, int dst_offset)
{
    int i = src_offset;
    int j = dst_offset;
    int ni = src.Length;
    int nj = dst.Length;
    while ((i < ni) && (j < nj))
    {
        j += long.TryParse(src[i], out dst[j]) ? 1 : 0;
        i++;
    }
    return j;
}
var line = "lemon 4 grape 1 garlic 77";
string[] words = line.Split(' ');
long[] longs = new long[10];
int l = strv_to_longv(words, 1, longs, 0);
//longs will be equal {4, 1, 77}
//l will be equal 3

另一种实现方法是使用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);
}