Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq to sql to returning boolean

Tags:

c#

linq-to-sql

I have a table Fruits that contains the following columns

UserID | FruitID

I want to verify that the UserID is authorized on the FruitID so I'm 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 query returns an ID and if he's not authorized, it returns null. I then check to see if the return value is null and then set a bool based on the returned value.

What I want to do is return bool: if the user is authorized then it should return true.

How can I modify the query to return a boolean?

Thanks.

like image 561
frenchie Avatar asked Nov 27 '22 14:11

frenchie


1 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 SQL server) you could use the .Any extension method which is better:

var IsAuthorized = MyDC
    .Fruits
    .Any(f => f.UserID == TheUserID && f.FruitID == TheFruitID);
like image 128
Darin Dimitrov Avatar answered Dec 07 '22 02:12

Darin Dimitrov