运算符'=='不能应用于'int'类型和'string'错误的操作数

nou*_*ime -1 c# linq

为什么我会在这段代码中看到上述错误?该错误具体发生在以下t.TerritoryID == territoryID部分:

[HttpPost]
public ActionResult Add(EmployeeViewModel employee, string[] territories)
{
        ModelState.Remove("territories");

        if (ModelState.IsValid)
        {
            if (territories != null)
            {
                employee.Territories = territories.Select(territoryID => repository.Territories.FirstOrDefault(t => t.TerritoryID == territoryID));
            }

            employee.EmployeeID = repository.CreateEmployee(employee);
        }

        return RedirectToAction("Index");
}
Run Code Online (Sandbox Code Playgroud)

如果你想知道,TerritoryID是一个整数.关于如何纠正这个问题的任何建议?提前致谢.

fej*_*oco 8

Int和string是两种不同的类型,你不能直接比较它们.您可以将int转换为字符串,反之亦然.

更改territories为int数组:var territoriesInt = territories.Select(x => int.Parse(x)).ToArray(),然后使用它.

上面的代码是字符串到int的转换.如果字符串不包含数字,则可能会失败.如果有人发送错误数据,我宁愿故意让它失败.如果你将你的领地字符串与之比较,它也可以以相反的方式完成territoryID.ToString().