简体   繁体   中英

Linq query and multiple where clauses with OR only first condition gets evaluated

I give a user flexibility by providing either username or user id, which are different database fields, both strings. Here is my Linq query below:

var usr = ctx.Users.Where(a => (a.Username.Equals(id) || a.UserID.Equals(id))).ToList();

The thing is if I call it with username: "johndoe", I get a record back, but if I user UserID: "12345" then I do not get any records back even though there is a user "johndoe" with id "12345" in the database.

Also if I change it to:

var usr = ctx.Users.Where(a => a.UserID.Equals(id)).ToList();

It works fine with UserID; "12345". So it seems that only first condition gets evaluated. Can't figure out what am I doing wrong...

Just to make things clear: I want to check both fields for the given id value and return the record where either field matches the id.

The final result I want to get is to have a record(s) returned in my usr variable regardless of which field, Username or UserID matches the input id.

Your linq query looks ok to me

public class Users
    {
      public string Username {get;set;}
      public string Userid {get;set;}
    }

void Main()
{
    var users = new List<Users>{new Users {Username="johndoe",Userid="123"},
                                new Users {Username="stevejobs",Userid="456"}
                                };

    var filter = users.Where(a => (a.Username.Equals("123") || a.Userid.Equals("123"))).ToList();
    filter.Dump();
    var filter2 = users.Where(a => (a.Username.Equals("456") || a.Userid.Equals("456"))).ToList();
    filter2.Dump();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM