I have the following Linq query and trying to perform a left join. I keep getting the following error on the .Select -> Speed line. As it is a left join my 'firstlist' will have more IDs than my 'secondlist'. How do I handle the NULL? I used .SelectMany after researching this is how to do the left join in LINQ but it doesnt seem to be working:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
<>f__AnonymousType0<j__TPar, j__TPar>.secondlist.get returned null.
public class Model
{
public string name { get; set; }
public int ID { get; set; }
public double Speed { get; set; }
}
private List<Model> newlist ;
Below linq query in method:
newlist = firstlist
.GroupJoin(secondlist, x => x.ID, y => y.ID, (a, b) => new { firstlist = a, secondlist = b })
.SelectMany(x => x.secondlist.DefaultIfEmpty(), (x, y) => new { firstlist = x.firstlist, secondlist = y })
.OrderBy(h => h.firstlist.Year)
.GroupBy(a => new
{
a.firstlist.Name,
a.firstlist.ID,
a.firstlist.Speed,
})
.Select(g => new Model
{
Name = g.Key.Name,
ID = g.Key.ID,
Speed = g.Where(c => g.Key.Speed > c.secondlist.Speed).Sum(c => c.secondlist.Value),
})
.ToList();