27

I'm trying to use .Any() in an if statement like so:

if(this.db.Users.Any(x => x.UserID == UserID)){
    // do stuff
}

Is there a way I can put multiple conditions inside of the .Any()? For example something like:

if(this.db.Users.Any(x => x.UserID == UserID AND x.UserName == UserName)){
    // do stuff
}

Or is there a better way to go about this?

2 Answers 2

44

Sure, use the && operator.

if(this.db.Users.Any(x => x.UserID == UserID && x.UserName == UserName)){
    // do stuff
}

If you can use it in an if statement, you can use it here. The lambda needs to evaluate to a bool.

4
  • 1
    Doh! I tried that earlier but I was getting an error, apparently something else was incorrect at the time. Thanks!
    – Sgraffite
    Commented Dec 7, 2010 at 14:44
  • How can we specify blocks of conditions. e.g. .Any((x => x.UserID == UserID && x.UserName == UserName) || <<Some condition>> && <<Some condition>>)
    – VJOY
    Commented Jun 21, 2013 at 6:30
  • 1
    @VijayBalkawade just like that. if you can use it in an if statement, then you can use it here. Commented Jun 21, 2013 at 17:11
  • Will this translate to an Exists? Or a Count > 0? Commented Jul 4, 2018 at 9:04
7
if(this.db.Users.Any(x => x.UserID == UserID && x.UserName == UserName)){
    // do stuff
}
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.