Using extension syntax I\'m trying to create a left-join using LINQ on two lists that I have. The following is from the Microsoft help but I\'ve modified it to show that the
You need to get the joined objects into a set and then apply DefaultIfEmpty as JPunyon said:
Person magnus = new Person { Name = "Hedlund, Magnus" };
Person terry = new Person { Name = "Adams, Terry" };
Person charlotte = new Person { Name = "Weiss, Charlotte" };
Pet barley = new Pet { Name = "Barley", Owner = terry };
List people = new List { magnus, terry, charlotte };
List pets = new List{barley};
var results =
from person in people
join pet in pets on person.Name equals pet.Owner.Name into ownedPets
from ownedPet in ownedPets.DefaultIfEmpty(new Pet())
orderby person.Name
select new { OwnerName = person.Name, ownedPet.Name };
foreach (var item in results)
{
Console.WriteLine(
String.Format("{0,-25} has {1}", item.OwnerName, item.Name ) );
}
Outputs:
Adams, Terry has Barley
Hedlund, Magnus has
Weiss, Charlotte has