I'm reading C# In Depths to try and better understand the language. I've used simple lambda expressions before with a single parameter and have become familiar with them. The part I'm struggling with is films.Sort((f1, f2) => f1.Name.CompareTo(f2.Name)); to sort the list. From what I've been able to figure out the lambda expression evaluates to IComparer<Film> when I tried to add f3 to it. The method being called IComparer.Compare Method (T, T) determines the items order.
The second parameter makes me want to say that it's comparing the Nth and Nth+1 film in the list and doing that from 0 through films.Count-1. Is this correct? If not, what part am I mistaken on. I wan't to avoid assuming incorrectly and avoid unintended errors.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var films = GetFilms();
Action<Film> print = film => Console.WriteLine("Name={0}, Year={1}", film.Name, film.Year);
Console.WriteLine("All films");
films.ForEach(print);
Console.WriteLine();
Console.WriteLine("Old films");
films.FindAll(film => film.Year < 1960).ForEach(print);
Console.WriteLine();
Console.WriteLine("Sorted films");
films.Sort((f1, f2) => f1.Name.CompareTo(f2.Name));
films.ForEach(print);
}
class Film
{
public string Name { get; set; }
public int Year { get; set; }
}
static List<Film> GetFilms()
{
return new List<Film>
{
new Film { Name = "Jaws", Year = 1975 },
new Film { Name = "Singing in the Rain", Year = 1952 },
new Film { Name = "Some like it Hot", Year = 1959 },
new Film { Name = "The Wizard of Oz", Year = 1939 },
new Film { Name = "It's a Wonderful Life", Year = 1946 },
new Film { Name = "American Beauty", Year = 1999 },
new Film { Name = "High Fidelity", Year = 2000 },
new Film { Name = "The Usual Suspects", Year = 1995 }
};
}
}