Take the following pseudo C# code:
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);
}
Would it be faster if the two Select() calls were combined? Is there an extra iteration in the code above? Is the following code faster?
public IEnumerable<IEmployer> Employers()
{
string sql = "select EmployerID from employer";
return GetRecords(sql).Select(record => new Employer((record["EmployerID"] as int?) ?? 0) as IEmployer);
}
I think the first example is more readable if there is no difference in performance.
There is no significant difference. Both methods returns an expression that can loop through the result from GetRecords.
They are not identical, as the first one has chained Selects, but they will still do the same work and in the same order. When looping the chained Selects, the second select will put items one and one from the first Select as needed, the first Select doesn’t have to complete before the second Select can use the result.