tags:

views:

206

answers:

5

The following obviously will not compile, so what should I change?

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

Try

public bool IsFoobar(bool foo, bool bar)
{
    return db.Foobars.Any(fb => fb.foo == foo && fb.bar == bar);
}
gautema
Thanks Gaute and everyone else.
Nicholas Murray
+4  A: 

Without knowing how your datamodel looks and how you actually wish this to behave, I'd 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 the other poster said, by using != null you'd still get the exception thrown if your database has two matching rows. However, if you do not want that check you should probably use the suggested .Any method instead.

wasatz
+1  A: 

Maybe you are looking for Any:

return db.Foobars.Any(fb => ((fb.foo == foo) && (fb.bar == bar)));
bruno conde
How is this different from Gaute Magnussen's earlier answer?
ChrisF
@ChrisF, It isn't. He was faster and I didn't saw it.
bruno conde
Sorry for sounding a bit harsh but I'm getting a bit annoyed about duplicate answers, and yours was the first I've seen since I decided I'd comment when I see them. I'll try to come up with a more tactful phrase.
ChrisF
A: 

Not entirely sure what you are trying to achieve here but to break it down in to parts that may help, firstly you could define the lambda as (assuming db.FooBars is a collection 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 bar values in the closure:

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

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

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

bool result = myTest(myFooBar);

OR using the second lambda example:

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

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

Hope this helps...

Simon Fox
A: 

This is unlikely to be the answer, but it's perhaps important to realise that the original code could compile fine given the right 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 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 probably be better if it didn't.

Daniel Earwicker