[ACCEPTED]-Convert a C# Method to return a boolean from a lambda expression-lambda

Accepted answer
Score: 15

Try

public bool IsFoobar(bool foo, bool bar)
{
    return db.Foobars.Any(fb => fb.foo == foo && fb.bar == bar);
}

0

Score: 4

Without knowing how your datamodel looks 7 and how you actually wish this to behave, I'd 6 hazard a guess at

public bool IsFoobar(bool foo, bool bar)
{
    return db.Foobars.SingleOrDefault(fb => ((fb.foo == foo) && (fb.bar == bar))) != null;
}

Edit: While you could use .Any as 5 the other poster said, by using != null you'd still 4 get the exception thrown if your database 3 has two matching rows. However, if you do 2 not want that check you should probably 1 use the suggested .Any method instead.

Score: 2

Maybe you are looking for Any:

return db.Foobars.Any(fb => ((fb.foo == foo) && (fb.bar == bar)));

0

Score: 0

Not entirely sure what you are trying to 8 achieve here but to break it down in to 7 parts that may help, firstly you could define 6 the lambda as (assuming db.FooBars is a collection 5 of type FooBar):

bool foo = ...someBooleanValue...;
bool bar = ...someOtherBooleanValue...;

Func<FooBar, bool> myTest = fb => ((fb.foo == foo) && (fb.bar == bar));

OR without including the foo and 4 bar values in the closure:

Func<FooBar, bool, bool, bool> myTest = 
                 (fb, foo, bar) => ((fb.foo == foo) && (fb.bar == bar));

and then get a 3 result on a particular instance of FooBar via 2 (using the 1st lambda example):

FooBar myFooBar = ...some instance...;

bool result = myTest(myFooBar);

OR using 1 the second lambda example:

FooBar myFooBar = ...some instance...;
bool foo = ...someBooleanValue...;
bool bar = ...someOtherBooleanValue...;

bool result = myTest(myFooBar, foo, bar);

Hope this helps...

Score: 0

This is unlikely to be the answer, but it's 5 perhaps important to realise that the original 4 code could compile fine given the right 3 definitions preceding it:

// Ugh! Public data for brevity

class Foobar
{
    public bool foo, bar;
    public static implicit operator bool(Foobar fb) { return fb.foo; }
}

class Db
{
    public IEnumerable<Foobar> Foobars;
}

Db db;

Now the original 2 code compiles fine:

public bool IsFoobar(bool foo, bool bar)
{
    return db.Foobars.SingleOrDefault(fb => ((fb.foo == foo) && (fb.bar == bar)));
}

But admittedly it would 1 probably be better if it didn't.

More Related questions