了解一下Linq。 我有以下代码:Linq查询首选项
(请原谅数据集的可怜的大小)
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; }
}
}
我有几个问题:
据我所知,这两个功能的Linq查询正在做同样的事情(黑魔法可能正在进行)。
- 它们都被编译到相同的IL?
- 如果不是,为什么以及哪个数据量最大时效率最高?
- 什么是监测Linq查询效率的最佳方法?性能计时器或内置的东西?
- lambda表达式是首选方法,因为它是最简洁的?
- 在lambda担心luddites的一个部门中,值得冒险和教导他们或使用SQL-esque语法吗?
感谢
由于您使用这两种方法的lambda表达式,我不知道您的问题4和5得到什么。您可能可以重写第二个版本,而不使用lambda,我怀疑很多人会认为它会更干净,更易读。 – 2010-07-31 08:51:11