Whats the difference between these two approaches for performing Left Outer Join with LINQ, for both I am using two lists of Buyers and Suppliers, and joining them by a common district to find the suppliers and buyers that are in the same district.
class Supplier
{
public string Name { get; set; }
public string District { get; set; }
}
class Buyer
{
public string Name { get; set; }
public string District { get; set; }
}
List<Buyer> buyers = new List<Buyer>()
{
new Buyer() { Name = "Johny", District = "Fantasy District" },
new Buyer() { Name = "Peter", District = "Scientists District" },
new Buyer() { Name = "Paul", District = "Fantasy District" },
new Buyer() { Name = "Maria", District = "Scientists District" },
new Buyer() { Name = "Joshua", District = "EarthIsFlat District" },
new Buyer() { Name = "Sylvia", District = "Developers District" },
new Buyer() { Name = "Rebecca", District = "Scientists District" },
new Buyer() { Name = "Jaime", District = "Developers District" },
new Buyer() { Name = "Pierce", District = "Fantasy District" }
};
List<Supplier> suppliers = new List<Supplier>()
{
new Supplier() { Name = "Harrison", District = "Fantasy District" },
new Supplier() { Name = "Charles", District = "Developers District" },
new Supplier() { Name = "Hailee", District = "Scientists District" },
new Supplier() { Name = "Taylor", District = "EarthIsFlat District" }
};
First:
var suppliersAndBuyers = from s in suppliers
orderby s.District
join b in buyers on s.District equals b.District into buyersGroup
select buyersGroup.DefaultIfEmpty(
new Buyer()
{
Name = string.Empty,
District = s.District
});
foreach (var item in suppliersAndBuyers)
{
foreach (var buyer in item)
{
Console.WriteLine($"{buyer.District} {buyer.Name}");
}
}
And Second approach:
var suppliersAndBuyers = from s in suppliers
orderby s.District
join b in buyers on s.District equals b.District into buyersGroup
from bG in buyersGroup.DefaultIfEmpty()
select new
{
Name = bG.Name == null ? string.Empty : bG.Name,
s.District,
};
foreach (var item in suppliersAndBuyers)
{
Console.WriteLine($"{item.District} {item.Name}");
}
Both produce the exact same output, is the only difference in the way that we output the results? Which one should I use?
Edit: The first approach returns IEnumerable<IEnumerable<Buyer>>
the second one returns IEnumerable<AnonymousType>
, is the only meaningful difference between the two in what type they are returning and is this the only deciding factor between the two approaches, wether I want a type or anonymous type?