采用以下伪 C# 代码:
using System;
using System.Data;
using System.Linq;
using System.Collections.Generic;
public IEnumerable<IDataRecord> GetRecords(string sql)
{
// DB logic goes here
}
public IEnumerable<IEmployer> Employers()
{
string sql = "select EmployerID from employer";
var ids = GetRecords(sql).Select(record => (record["EmployerID"] as int?) ?? 0);
return ids.Select(employerID => new Employer(employerID) as IEmployer);
}
如果两个 Select() 调用结合起来会更快吗?上面的代码中是否有额外的迭代?下面的代码更快吗?
public IEnumerable<IEmployer> Employers()
{
string sql = "select EmployerID from employer";
return GetRecords(sql).Select(record => new Employer((record["EmployerID"] as int?) ?? 0) as IEmployer);
}
如果性能没有差异,我认为第一个示例更具可读性。