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?