linq to sql to returning boolean

2019-05-05 23:33发布

问题:

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.

回答1:

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);


回答2:

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();