转换 C# 方法以从 lambda 表达式返回布尔值
以下显然无法编译,那么我应该改变什么?
public bool IsFoobar(bool foo, bool bar)
{
return db.Foobars.SingleOrDefault(fb => ((fb.foo == foo) && (fb.bar == bar)));
}
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)));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
尝试
Try
在不知道您的数据模型的外观以及您实际希望其行为如何的情况下,我会冒险猜测
编辑:
虽然您可以像其他发帖人所说的那样使用
.Any
,但如果您的数据库有两个匹配的行,则通过使用!= null
您仍然会抛出异常。但是,如果您不想进行该检查,则可能应该使用建议的.Any
方法。Without knowing how your datamodel looks and how you actually wish this to behave, I'd hazard a guess at
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.也许您正在寻找
任何
:Maybe you are looking for
Any
:这不太可能是答案,但重要的是要认识到,如果前面有正确的定义,原始代码可以很好地编译:
现在原始代码可以很好地编译:
但不可否认,如果不这样做可能会更好。
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:
Now the original code compiles fine:
But admittedly it would probably be better if it didn't.
不完全确定您要在这里实现什么,但将其分解为可能有帮助的部分,首先您可以将 lambda 定义为(假设 db.FooBars 是 FooBar 类型的集合):
或者在闭包中不包含 foo 和 bar 值:
然后通过(使用第一个 lambda 示例)在
FooBar
的特定实例上获取结果:或者使用第二个 lambda示例:
希望这有帮助...
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 typeFooBar
):OR without including the foo and bar values in the closure:
and then get a result on a particular instance of
FooBar
via (using the 1st lambda example):OR using the second lambda example:
Hope this helps...