Left Outer Join

Query
public void Linq105() 
{
string[] categories = new string[]{
"Beverages",
"Condiments",
"Vegetables",
"Dairy Products",
"Seafood" };

List products = GetProductList();

var q =
from c in categories
join p in products on c equals p.Category into ps
from p in ps.DefaultIfEmpty()
select new { Category = c, ProductName = p == null ? "(No products)" : p.ProductName };

foreach (var v in q)
{
Console.WriteLine(v.ProductName + ": " + v.Category);
}
}
Lambda Expression
public void Linq105()
{
List customers = GetCustomerList();
List suppliers = GetSupplierList();

var supplierCusts =
suppliers.GroupJoin(customers, sup => sup.Country, cust => cust.Country, (sup, cs) => new {sup, cs})
.SelectMany(@t => @t.cs.DefaultIfEmpty(),(@t, c) => new {@t, c})
.OrderBy(@t => @t.@t.sup.SupplierName)
.Select(@t => new{
Country = @t.@t.sup.Country,
CompanyName = @t.c == null? "(No customers)": @t.c.CompanyName,
SupplierName = @t.@t.sup.SupplierName});

foreach (var item in supplierCusts)
{
Console.WriteLine("{0} ({1}): {2}", item.SupplierName, item.Country, item.CompanyName);
}
}
Output
Chai: Beverages
Chang: Beverages
Guaraná Fantástica: Beverages
Sasquatch Ale: Beverages
Steeleye Stout: Beverages
Côte de Blaye: Beverages
Chartreuse verte: Beverages
Ipoh Coffee: Beverages
Laughing Lumberjack Lager: Beverages
Outback Lager: Beverages
Rhönbräu Klosterbier: Beverages
Lakkalikööri: Beverages
Aniseed Syrup: Condiments
Chef Anton's Cajun Seasoning: Condiments
Chef Anton's Gumbo Mix: Condiments
Grandma's Boysenberry Spread: Condiments
Northwoods Cranberry Sauce: Condiments
Genen Shouyu: Condiments
Gula Malacca: Condiments
Sirop d'érable: Condiments
Vegie-spread: Condiments
Louisiana Fiery Hot Pepper Sauce: Condiments
Louisiana Hot Spiced Okra: Condiments
Original Frankfurter grüne Soße: Condiments
(No products): Vegetables
Queso Cabrales: Dairy Products
Queso Manchego La Pastora: Dairy Products
Gorgonzola Telino: Dairy Products
Mascarpone Fabioli: Dairy Products
Geitost: Dairy Products
Raclette Courdavault: Dairy Products
Camembert Pierrot: Dairy Products
Gudbrandsdalsost: Dairy Products
Flotemysost: Dairy Products
Mozzarella di Giovanni: Dairy Products
Ikura: Seafood
Konbu: Seafood
Carnarvon Tigers: Seafood
Nord-Ost Matjeshering: Seafood
Inlagd Sill: Seafood
Gravad lax: Seafood
Boston Crab Meat: Seafood
Jack's New England Clam Chowder: Seafood
Rogede sild: Seafood
Spegesild: Seafood
Escargots de Bourgogne: Seafood
Röd Kaviar: Seafood
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 # # # # #