了解一些有关 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 的勒德分子的部门,是否值得冒险教导他们或使用 SQL 式语法?
谢谢
最佳答案
回复
var oaps1 = employees.Where(oapCalculator);
对比
var oaps2 = (from employee in employees
where oapCalculator(employee)
select employee);
存在轻微差异,特别是在 where oapCalculator(employee)
周围。第二个查询映射到:
var oaps2 = employees.Where(employee => oapCalculator(employee));
因此,这是委托(delegate)的额外层,并且由于变量 oapCalculator
的闭包,还会产生捕获类的(小)开销。 ,以及每次迭代对此的取消引用。但除此之外它们是相同的。特别是Select
被轻松删除(根据规范)。
一般来说,在任何场景中都使用最清晰的那个。在这种情况下,两者似乎都不错,但是您会发现使用 .Where
更容易等等,如果您经常处理涉及代表的场景或 Expression
s。
关于c# - Linq 查询首选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3377417/