Lambda 与 LINQ - “表达式始终为假”
我有以下代码:
var thing = (from t in things
where t.Type == 1 && t.IsActive
select t).SingleOrDefault();
if (thing == null)
{
// throw exception
}
things
是实体框架自我跟踪实体的集合
这工作得很好,但是我想改用 Lambda 表达式,并将 LINQ 更改为:
var thing = things.Select(t => t.Type == 1 && t.IsActive).SingleOrDefault();
现在 Resharper 告诉我 <对于 (thing == null)
,code>表达式始终为 false。
我错过了什么?
I have the following code:
var thing = (from t in things
where t.Type == 1 && t.IsActive
select t).SingleOrDefault();
if (thing == null)
{
// throw exception
}
things
is a collection of Entity Framework Self-Tracking Entities
This works nicely, however I want to use a Lambda expression instead and changed the LINQ to this:
var thing = things.Select(t => t.Type == 1 && t.IsActive).SingleOrDefault();
Now Resharper is telling me Expression is always false
for (thing == null)
.
What have I missed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您希望:
Select
执行投影(将 IEnumerable 的类型从IEnumerable
转换为IEnumerable
,其值为true
如果t.Type == 1 && t.IsActive == true
,否则false
),则SingleOrDefault
返回此序列中唯一的bool
,或者返回bool
的默认值,如果序列为空。它永远不能为 null,因为bool
不是引用类型。Where
执行过滤操作(仅提取那些满足给定条件的对象 - 在本例中,仅选择Type
为1
且 < code>IsActive 为true
),将 IEnumerable 的类型保留为IEnumerable
。假设Thing
是一个类,则SingleOrDefault
将返回序列中的唯一项或null
。无论哪种情况,如果序列包含多个项目,
SingleOrDefault
都会引发异常(在Select
版本中这种情况的可能性要大得多!)。You want:
Select
performs a projection (converting the type of the IEnumerable fromIEnumerable<Thing>
toIEnumerable<bool>
with valuestrue
ift.Type == 1 && t.IsActive == true
, otherwisefalse
), then theSingleOrDefault
returns either the onlybool
in this sequence, or the default value of abool
which isfalse
if the sequence is empty. This can never be null sincebool
is not a reference type.Where
performs a filtering action (pulling out only those objects that meet a given criterion - in this case only selecting those whereType
is1
andIsActive
istrue
), leaving the type of the IEnumerable asIEnumerable<Thing>
. AssumingThing
is a class, theSingleOrDefault
will return the only item in the sequence ornull
.In either case,
SingleOrDefault
will throw an exception if the sequence contains more than one item (which is far more likely in theSelect
version!).