Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to SQL .Any() with multiple conditions?

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?

like image 511
Sgraffite Avatar asked Dec 07 '10 05:12

Sgraffite


People also ask

Can we use multiple where clause in LINQ query?

Well, you can just put multiple "where" clauses in directly, but I don't think you want to. Multiple "where" clauses ends up with a more restrictive filter - I think you want a less restrictive one.

What is any () in LINQ?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.

Can we have multiple conditions for the ON clause?

You can specify multiple conditions in a single WHERE clause to, say, retrieve rows based on the values in multiple columns. You can use the AND and OR operators to combine two or more conditions into a compound condition. AND, OR, and a third operator, NOT, are logical operators.


2 Answers

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.

like image 50
Kyle Trauberman Avatar answered Sep 17 '22 11:09

Kyle Trauberman


if(this.db.Users.Any(x => x.UserID == UserID && x.UserName == UserName)){     // do stuff } 
like image 43
Cheng Chen Avatar answered Sep 19 '22 11:09

Cheng Chen