2

Could you help me to translate this Linq query to extension methods:

    var query = from person in people
                join pet in pets on person equals pet.Owner into gj
                from subpet in gj.DefaultIfEmpty()
                select new { person.FirstName, PetName = (subpet == null ? String.Empty : subpet.Name) };

The query come from MSDN page about Left outer join.

I already did this:

    var result = people.join(pets, x, y => y.Owner, (x, y) => {
                    x.FirstName,
                    PetName = y == null ? String.Empty : y.Name
                }).ToList();

But I don't know what to do with the DefaultIfEmpty()?

Adding the DefaultIfEmpty() as explained on other solutions result in CS0746 Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Bastien Vandamme
  • 17,659
  • 30
  • 118
  • 200
  • Why do you have to use method syntax? joins are _much_ cleaner in query syntax and method syntax gives you no benefit in terms of performance. – D Stanley Jan 05 '17 at 04:35

1 Answers1

1

You could do like this with GroupJoin

people.GroupJoin(pets,p => p,pt => pt.Owner,
                 (p, pt) => new { p.FirstName, names = pt.Select(y => y.Name)})
      .SelectMany(p => p.names.DefaultIfEmpty().Select(x => new {p.FirstName,PetName=x}))
Sateesh Pagolu
  • 9,282
  • 2
  • 30
  • 48