user2252020
user2252020

Reputation: 35

Error: "Operator '==' can't be applied to operators of type 'object' and 'int'

I have the following block in my code :

if (!Userpages.AccessableItems.Where(x => { return x.SelectReturns["Permission_ID"] == 1; }).FirstOrDefault().SelectReturns("AllowDeny"))
{
                Response.Redirect("~/NotAuthorized.aspx");              
} 

where Userpages is a variable of customized business object, and selectReturns is property of type Dictionary<string,object> but I got an error that

"Operator '==' can't be applied to operators of type 'object' and 'int'.

I tried to cast '1' as object but it seems also not correct ". can anyone help me ?!

Upvotes: 1

Views: 195

Answers (3)

Sachin
Sachin

Reputation: 40970

Your comparison look like this

x.SelectReturns["Permission_ID"] == 1

where left side is an object. So cast your object into Int and then do the comparison.

Convert.ToInt32(x.SelectReturns["Permission_ID"])==o

Upvotes: 7

IS4
IS4

Reputation: 13177

If x.SelectReturns["Permission_ID"] returns object of type System.Int32, you can cast it:

if(!Userpages.AccessableItems.Where(x => (int)x.SelectReturns["Permission_ID"] == 1).FirstOrDefault().SelectReturns("AllowDeny"))
{
    Response.Redirect("~/NotAuthorized.aspx");              
}

But if it can be another type or any custom type, you can use directly (overloaded) Equals method:

if(!Userpages.AccessableItems.Where(x => x.SelectReturns["Permission_ID"].Equals(1)).FirstOrDefault().SelectReturns("AllowDeny"))
{
    Response.Redirect("~/NotAuthorized.aspx");              
}

Upvotes: 0

Maarten
Maarten

Reputation: 22945

If the output of the dictionary-lookup is assured to be of type int, you can do the following:

if (!Userpages.AccessableItems
      .Where(x => (int)(x.SelectReturns["Permission_ID"]) == 1)
      .FirstOrDefault().SelectReturns("AllowDeny")
) {
      Response.Redirect("~/NotAuthorized.aspx");
}

Note: I've also made the linq a bit simpler.

Upvotes: 0

Related Questions