text
stringlengths
0
13.4k
//Pro Pong 2016 by Barfizz
Section 8.49: Left Outer Join
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
class Pet
{
public string Name { get; set; }
public Person Owner { get; set; }
}
public static void Main(string[] args)
{
var magnus = new Person { FirstName = "Magnus", LastName = "Hedlund" };
var terry = new Person { FirstName = "Terry", LastName = "Adams" };
var barley = new Pet { Name = "Barley", Owner = terry };
var people = new[] { magnus, terry };
var pets = new[] { barley };
GoalKicker.com – .NET Framework Notes for Professionals
44
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?.Name ?? "-" // Use - if he has no pet
};
foreach (var p in query)
Console.WriteLine($"{p.FirstName}: {p.PetName}");
}
GoalKicker.com – .NET Framework Notes for Professionals
45
Chapter 9: ForEach
Section 9.1: Extension method for IEnumerable
ForEach() is defined on the List<T> class, but not on IQueryable<T> or IEnumerable<T>. You have two choices in
those cases:
ToList first
The enumeration (or query) will be evaluated, copying the results into a new list or calling the database. The
method is then called on each item.
IEnumerable<Customer> customers = new List<Customer>();
customers.ToList().ForEach(c => c.SendEmail());
This method has obvious memory usage overhead, as an intermediate list is created.
Extension method
Write an extension method:
public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
foreach(T item in enumeration)
{
action(item);
}
}
Use:
IEnumerable<Customer> customers = new List<Customer>();
customers.ForEach(c => c.SendEmail());
Caution: The Framework's LINQ methods have been designed with the intention of being pure, which means they
do not produce side effects. The ForEach method's only purpose is to produce side effects, and deviates from the
other methods in this aspect. You may consider just using a plain foreach loop instead.
Section 9.2: Calling a method on an object in a list
public class Customer {
public void SendEmail()
{
// Sending email code here
}