Learning a bit about Linq.
I have the following code:
(Please excuse the pathetic size of the data set)
class Program
{
static void Main(string[] args)
{
var employees = new List<Employee>
{
new Employee
{
Name = "Bill Bailey",
EmployeeCode = 12345,
Department = "Comedy Lab",
DateOfBirth = DateTime.Parse("13/01/1964"),
CurrentEmployee = true
},
new Employee
{
Name = "Boris Johnson",
EmployeeCode = 56789,
Department = "Cycling Dept.",
DateOfBirth = DateTime.Parse("19/06/1964"),
CurrentEmployee = true
},
new Employee
{
Name = "Bruce Forsyth",
EmployeeCode = 5,
Department = "Comedy Lab",
DateOfBirth = DateTime.Parse("22/03/1928"),
CurrentEmployee = false
},
new Employee
{
Name = "Gordon Brown",
EmployeeCode = 666,
Department = "Backbenches",
DateOfBirth = DateTime.Parse("20/02/1951"),
CurrentEmployee = false
},
new Employee
{
Name = "Russell Howard",
EmployeeCode = 46576,
Department = "Comedy Lab",
DateOfBirth = DateTime.Parse("23/03/1980"),
CurrentEmployee = false
}
};
Func<Employee, bool> oapCalculator = (employee => employee.DateOfBirth.AddYears(65) < DateTime.Now);
var oaps1 = employees.Where(oapCalculator);
var oaps2 = (from employee in employees
where oapCalculator(employee)
select employee);
oaps1.ToList().ForEach(employee => Console.WriteLine(employee.Name));
oaps2.ToList().ForEach(employee => Console.WriteLine(employee.Name));
Console.ReadLine();
}
class Employee
{
public string Name { get; set; }
public int EmployeeCode { get; set; }
public string Department { get; set; }
public DateTime DateOfBirth { get; set; }
public bool CurrentEmployee { get; set; }
}
}
I have a few questions:
As far as I can tell, both of the featured Linq queries are doing the same thing (black magic may be afoot).
- Would they both be compiled down to the same IL?
- If not, why, and which would be the most efficient given a sizable amount of data?
- What is the best way to monitor Linq query efficiency? Performance timers or something built-in?
- Is the lambda expression the preferred method, as it is the most concise?
- In a department of lambda fearing luddites, is it worth taking the plunge and teaching ’em up or using the SQL-esque syntax?
Thanks
Re
vs
There is a slight difference, in particular around the
where oapCalculator(employee). The second query is mapped to:so this is an extra layer of delegate, and will also incur the (small) overhead of a capture-class due to the closure over the variable
oapCalculator, and a dereference of this per iteration. But otherwise they are the same. In particular, theSelectis trivially removed (in accordance with the spec).In general, use whichever is clearest in any scenario. In this case, either seems fine, but you will find it easier to use
.Whereetc if you are regularly dealing in scenarios that involving delegates orExpressions.