I have this 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.
However, ga == null
is never true, so FirstOrDefault
gives me a null for difference
. ga
is, in fact, a DefaultIfEmptyIterator
and gaToList()
gives me a count of 1, and gaToList[0] == null
is true.
What have I done wrong here?
That's how DefaultIfEmpty
works. This method returns a collection with one element (type parameter's default) if the collection is empty, not 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.
If you want null
when joined
is empty try something like this:
joined.Any() ? joined : null
You can read more about DefaultIfEmpty
here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.