[英]Linq GroupJoin with DefaultIfEmpty
I have this GroupJoin: 我有这个GroupJoin:
var groupjoin = cData.GroupJoin(
aData,
c => c.Id,
a => a.Id,
(c, joined) => new { c, a = joined.DefaultIfEmpty() })
.ToList();
In my test data, there are NO matches. 在我的测试数据中,没有匹配项。 So, I have this code: 所以,我有这段代码:
var difference = groupjoin.FirstOrDefault(g =>
g.a == null);
I was expecting difference
to be an anonymous object with a "c" property that was an object from cData
, and an "a" property that was null. 我期望difference
是一个匿名对象,该匿名对象的“ c”属性是cData
的对象,而“ a”属性为null。
However, ga == null
is never true, so FirstOrDefault
gives me a null for difference
. 然而, ga == null
是不正确的,所以FirstOrDefault
给了我一个空difference
。 ga
is, in fact, a DefaultIfEmptyIterator
and gaToList()
gives me a count of 1, and gaToList[0] == null
is true. 实际上, ga
是DefaultIfEmptyIterator
而gaToList()
给我的计数为1,而gaToList[0] == null
为true。
What have I done wrong here? 我在这里做错了什么?
That's how DefaultIfEmpty
works. 这就是DefaultIfEmpty
工作方式。 This method returns a collection with one element (type parameter's default) if the collection is empty, not null. 如果该集合为空而不是null,则此方法返回一个具有一个元素的集合(类型参数的默认值)。
So in your case, if there are no matches, joined.DefaultIfEmpty()
will return a collection with just one element, that is null
for reference types. 因此,在您的情况下,如果没有匹配项,则joined.DefaultIfEmpty()
将返回仅包含一个元素的集合,对于引用类型为null
。
If you want null
when joined
is empty try something like this: 如果您希望在joined
为空时为null
,请尝试以下操作:
joined.Any() ? joined : null
You can read more about DefaultIfEmpty
here . 您可以在此处阅读有关DefaultIfEmpty
更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.