Linq to sql returns a boolean

I have a Fruits table that contains the following columns

 UserID | FruitID 

I want to check that UserID is allowed in FruitID, so I am writing something like this:

 var IsAuthorized = (from f in MyDC.Fruits where f.UserID == TheUserID && f.FruitID == TheFruitID select f.FruitID).SingleOrDefault(); 

So, if the user is authorized, the request returns an identifier, and if he is not authorized, he returns null. Then I check to see if the return value is zero, and then set bool based on the return value.

What I want to do is return bool: if the user is authorized, he must return true.

How can I modify a query to return a boolean?

Thanks.

+4
source share
2 answers
 var IsAuthorized = from (f in MyDC.Fruits where f.UserID == TheUserID && f.FruitID == TheFruitID select f.FruitID).SingleOrDefault() != null; 

or if you want this to be done by the underlying LINQ provider (for example, if you are using an SQL server), you can use the .Any extension method, which is better:

 var IsAuthorized = MyDC .Fruits .Any(f => f.UserID == TheUserID && f.FruitID == TheFruitID); 
+15
source

Any () returns true if the source sequence contains any elements; otherwise false.

 var IsAuthorized = from (f in MyDC.Fruits where f.UserID == TheUserID && f.FruitID == TheFruitID select f.FruitID).Any(); 
+12
source

Source: https://habr.com/ru/post/1439429/


All Articles