1
votes

I have this 2 lists list1 and list2 and created this GroupJoin:

List1 is a list of Persons (Id, Name) and list2 is a list of Objects (Id, Car, Date).

PS: list1 contains arround 40 elements and list2 for the moment only one element.

I try to set the maxDate but get the error "Sequence contains no elements"

var result = list1.GroupJoin(list2, 
                l1 => l1.Id,
                l2 => l2.Id
                (a, b) => new
                {
                    listA = a,
                    maxDate = b?.Max(m => m.Date).Date ??
                        new DateTime(2000, 01, 01)
                                 }).ToList();
1

1 Answers

3
votes

Looking at the expression b?.Max, looks like you are expecting that the variable b, which represents the related elements of the inner list will be null when there are no matches.

But GroupJoin documentation explicitly states:

If there are no correlated elements in inner for a given element of outer, the sequence of matches for that element will be empty but will still appear in the results.

So b is never null and Max throws the exception in question when it is empty.

You can solve it in two ways.

First is to use the nullable overload of Max which returns null instead of throwing exception on empty sequence:

maxDate = b.Max(m => (DateTime?)m.Date.Date) ?? new DateTime(2000, 01, 01)

This works well for both Enumerable and Queryable implementations.

The second way which works only for Enumerable is to use a combination of Select, DefaultIfEmpty and Max:

maxDate = b.Select(m => m.Date.Date).DefaultIfEmpty(new DateTime(2000, 01, 01)).Max()