0

Here on my example, what I am trying to do here is do a left join using LINQ with Lambda Query Syntax. But I always get an Inner Join results. Here is my sample data:

        Person magnus = new Person { FirstName = "Magnus", LastName = "Hedlund" };
        Person terry = new Person { FirstName = "Terry", LastName = "Adams" };
        Person charlotte = new Person { FirstName = "Charlotte", LastName = "Weiss" };
        Person arlene = new Person { FirstName = "Arlene", LastName = "Huff" };

        Pet barley = new Pet { Name = "Barley", Owner = "terry" };
        Pet boots = new Pet { Name = "Boots", Owner = "terry" };
        Pet whiskers = new Pet { Name = "Whiskers", Owner = "charlotte" };
        Pet bluemoon = new Pet { Name = "Blue Moon", Owner = "terry" };
        Pet daisy = new Pet { Name = "Daisy", Owner = "magnus" };

And here's my declaration on my List:

List<Person> people = new List<Person> { magnus, terry, charlotte, arlene };
List<Pet> pets = new List<Pet> { barley, boots, whiskers, bluemoon, daisy };

Now here's my LINQ Query which I want is a Left Join:

var query1 = people.Join(pets, oP => oP.FirstName.ToLower(), oPe => oPe.Owner.ToLower(), 
            (peeps, peets)
            => new 
            {
                PersonFirstName = peeps.FirstName,
                PersonLastName = peeps.LastName,
                DogName = peets?.Name ?? string.Empty
            });

But instead I receive an Inner Join results:

enter image description here

I am missing

Arlene

that is supposedly part of the result. I think I am missing something on my LINQ Query.

Willy David Jr
  • 8,604
  • 6
  • 46
  • 57
  • Not technically a duplicate of https://stackoverflow.com/questions/3404975/left-outer-join-in-linq. That post has the answer for doing a left outer join using LINQ query syntax, but I think OP is asking for how to do it using LINQ fluent/method syntax. – Jon Aug 10 '18 at 16:46
  • Yes exactly, I have that code already, but I want to create it using LINQ Fluent. – Willy David Jr Aug 10 '18 at 16:47
  • 1
    Try this: var query = people.GroupJoin( pets, person => person.FirstName.ToUpper(), pet => pet.Owner.ToUpper(), (x, y) => new {Person = x, Pets = y}) .SelectMany( x => x.Pets.DefaultIfEmpty(), (x, y) => new {Person = x.Person, Pet = y}); foreach (var i in query) { Console.WriteLine($"{i.Person.FirstName}: {i.Pet?.Name}"); } – Jon Aug 10 '18 at 16:49
  • Uggh... poor formatting in comments. – Jon Aug 10 '18 at 16:49
  • It works! @Jon I hope I can mark it as an answer! – Willy David Jr Aug 10 '18 at 16:52
  • 1
    Great! It's cool. ¯\_(ツ)_/¯ – Jon Aug 10 '18 at 16:53
  • 1
    I will re-open this, and put it as your answer so that I can mark it. – Willy David Jr Aug 10 '18 at 16:53
  • I appreciate it! – Jon Aug 10 '18 at 17:11
  • 1
    I already voted it to re-open it. Waiting for it to re-open. – Willy David Jr Aug 10 '18 at 17:20

0 Answers0