C# 运算符“==”不能应用于“int”和“string”类型的操作数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15404997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:41:48  来源:igfitidea点击:

Operator '==' cannot be applied to operands of type 'int' and 'string'

c#.netlinq

提问by

I have a little misunderstanding here why do i have here an error do i need to parse it what is wrong with this code ?

我在这里有点误解为什么我在这里有错误我需要解析它这段代码有什么问题吗?

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));
}

Thanks for help and fast answer !

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

PS:I thing I'm just over thing it it seams just to be a stupid little error ...

PS:我想我刚刚结束了它的接缝只是一个愚蠢的小错误......

采纳答案by Habib

You need to convert selectedDepartmentto integer before comparing it in the LINQ query.

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

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

In your query:

在您的查询中:

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

d.DepartmentIdis of type int whereas selectedDepartmentis a string and you can compare both using ==operator.

d.DepartmentId是 int 类型,而selectedDepartment是字符串,您可以使用==运算符比较两者。

回答by Darren

d.DepartmentIdis an intand selectedDepartmentis a string.

d.DepartmentId是一个int并且selectedDepartment是一个字符串。

You will need to convert using Int32.Parse, Int32.TryParseor Convert.ToInt32

您需要使用Int32.Parse,Int32.TryParseConvert.ToInt32

Edit:

编辑:

int selectedDepartmentId = Convert.ToInt32(selectedDepartment);

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

回答by Peter

You selectedDepartment is of type string, and your id is of type int. You should convert your selectedDepartment to a int:

您 selectedDepartment 是字符串类型,您的 id 是 int 类型。您应该将 selectedDepartment 转换为 int:

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