0

I am trying to translate my query syntax into Lambda and I have looked at a couple of threads here, some of which:

C# Linq Lambda Left Outer Join

How do you perform a left outer join using linq extension methods

And I still dont understand exactly how to implement what I want.

var suppliersAndBuyers = from s in suppliers
                         orderby s.District
                         join b in buyers on s.District equals b.District into buyersGroup
                         select new
                         {
                             SupplierName = s.Name,
                             s.District,
                             Buyers = buyersGroup.DefaultIfEmpty(
                             new Buyer()
                             {
                                 Name = "No one here",
                                 District = "I dont exist",
                             })
                         };

This is my linq query and it works perfectly, each of suppliers has its own group of buyers, and those suppliers that dont have buyers, simply get the default Buyer object that I am creating in the DefaultIfEmpty method.

I tried doing the following with Method Syntax:

var leftOuterJoinBuyer = suppliers.GroupJoin(
    buyers,
    s => s.District,
    b => b.District,
    (s, buyersGroup) => new
    {
        s.Name,
        s.District,
        Buyers = buyersGroup
    })
    .SelectMany(s => s.Buyers.DefaultIfEmpty(new Buyer() { Name = "No name", District = "No place", }),
                (s, b) => new
                {
                    SupplierName = s.Name,
                    Buyers = s.Buyers,
                    s.District
                }
    );

And both approaches return the exact same types, but I dont get the default object for my no match suppliers, and those that have matches get added several times to the end result.

For example Harrison gets added 3 times to the final collection with the exact same collection of buyers, basicly 3 identical results that are not needed and are not produced in my query syntax. Screenshot -> https://prntsc/iocsby

What is the correct way to rewrite this query?

Darkbound
  • 3,026
  • 7
  • 34
  • 72

1 Answers1

1

This is the lambda version:

var lambdaQuery = suppliers.GroupJoin(buyers, s => s.District, b => b.District,
    (s, buyersGroup) => new {
        SupplierName = s.Name,
        s.District,
        Buyers = buyersGroup.DefaultIfEmpty(new Buyer() { Name = "No one here", District = "I don't exist" })
    });
NetMage
  • 26,163
  • 3
  • 34
  • 55
  • So, no need for the SelectMany like with the other examples in the threads, where they produce an entirely new object? – Darkbound Mar 10 '18 at 15:12
  • The `GroupJoin` subsumes the need for a `SelectMany` from what I can see to match your query comprehension version. – NetMage Mar 12 '18 at 17:28