值得注意的是,在考虑如何优化LINQ查询时应格外小心。例如,如果使用声明性版本的LINQ执行以下操作:
public class Record
{
public string Name { get; set; }
public double Score1 { get; set; }
public double Score2 { get; set; }
}
var query = from record in Records
order by ((record.Score1 + record.Score2) / 2) descending
select new
{
Name = record.Name,
Average = ((record.Score1 + record.Score2) / 2)
};
如果由于某种原因,您决定先通过将平均值存储到变量中来“优化”查询,那么您将无法获得所需的结果:
// The following two queries actually takes up more space and are slower
var query = from record in Records
let average = ((record.Score1 + record.Score2) / 2)
order by average descending
select new
{
Name = record.Name,
Average = average
};
var query = from record in Records
let average = ((record.Score1 + record.Score2) / 2)
select new
{
Name = record.Name,
Average = average
}
order by average descending;
我知道没有多少人对对象使用声明式LINQ,但这是值得深思的。