0

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();
RA19
  • 583
  • 3
  • 17
  • I usually use leftouter join from this example : https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/join-clause – jdweng Feb 23 '21 at 16:21
  • How do you use a group by with the example given? It looks like a different syntax to the linq query i have above. Guessing I need to change the way I write my linq query? I am new to LINQ, I would normally write this in SQL but trying out C# LINQ – RA19 Feb 23 '21 at 16:27
  • The Group has to be done after the JOIN. So in example put a parenthsis around the from and then do join : (from ........... select new .....).GroupBy(x => .......... – jdweng Feb 23 '21 at 16:30

0 Answers0