如何将字符串转换为可为空的 int LINQ



>我看到了很多这样的问题,但似乎我找不到任何将彼此联系起来并为我找到解决方案的东西。我正在使用MVC 4应用程序,其中有一个下拉列表,其中包含一些值。

我正在使用视图包来填充它。

ViewBag.Roles = new SelectList(db.Roles, "RoleId", "RoleName");

在视图中,我的下拉列表如下所示。

@Html.DropDownList("selectedRole", ViewBag.Roles as SelectList, String.Empty)

字符串selectedRole从视图中获取RoleId值。

在此之后,我正在使用selectedRole对数据库执行一些LINQ,该表示我无法在我真正想要的LINQ中将字符串转换为Int,以便我可以返回更好的结果。

     public ActionResult SearchResults(string selectedRole, string selectedCourse, string SearchParam)
        {
            var members = (from m in db.Members
                           select m);
            if (!String.IsNullOrEmpty(selectedRole))
            {
                members = (from m in db.Members
                           where m.UserRole == Int32.Parse(selectedRole)
                           select m);

            }
        //some more if's here...
        return View(members.ToList());
}

所以问题是如何将此selectedRole转换为整数。在 LINQ 中转换时是否要遵循任何规则?

PS:我也尝试了返回相同错误的Convert.ToInt32(selectedRole)

在这种情况下,问题无关紧要...

if (!String.IsNullOrEmpty(selectedRole))
{
    int selectedRole2 = Int32.Parse(selectedRole);
    members = (from m in db.Members
               where m.UserRole == selectedRole2
               select m);

你不是在 linq 里做的,而是在外面做的。

通常,您不仅使用 Linq,还使用 Linq-to-Sql 或 Linq-to-Entities,因为Members是一个表。可悲的是,至少Linq-to-Entities没有任何强制转换方法。您可以使用用户定义的函数获得类似的东西,但它有点复杂。Linq-to-Sql 应该支持Convert.ToInt32(请参阅 https://msdn.microsoft.com/en-us/library/vstudio/bb882655.aspx)

最新更新