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

时间:2013-03-14 09:04:23

标签: c# .net linq

我有一点误会,为什么我这里有一个错误,我需要解析它这个代码有什么问题?

UberTrackerEntities ctx = UberFactory.Context;
IEnumerable<HtUser> users = HtUser.GetAll();
string selectedBU = rcbBusinessUnits.SelectedValue;
string selectedDepartment = rcbDepartment.SelectedValue;

HtDepartment department = ctx.HtDepartments.SingleOrDefault(d => d.DepartmentId ==selectedDepartment);

if (department != null) 
{
    users = users.Where(u => u.HtDepartments.Contains(department));
}

感谢您的帮助和快速回答!

PS:我认为我只是因为它只是一个愚蠢的小错误......

3 个答案:

答案 0 :(得分:12)

在LINQ查询中进行比较之前,您需要将selectedDepartment转换为整数。

int selectedDepartment = Convert.ToInt32(rcbDepartment.SelectedValue);

在您的查询中:

ctx.HtDepartments.SingleOrDefault(d => d.DepartmentId == selectedDepartment);

d.DepartmentId的类型为int,而selectedDepartment是一个字符串,您可以使用==运算符进行比较。

答案 1 :(得分:0)

d.DepartmentIdintselectedDepartment是字符串。

您需要使用Int32.ParseInt32.TryParseConvert.ToInt32

进行转换

编辑:

int selectedDepartmentId = Convert.ToInt32(selectedDepartment);

HtDepartment department = ctx.HtDepartments.SingleOrDefault(d => d.DepartmentId == selectedDepartmentId));

答案 2 :(得分:0)

您选择的部门是字符串类型,您的ID是int类型。您应该将selectedDepartment转换为int:

int selectedDepartment = Convert.ToInt32(rcbDepartment.SelectedValue);