I have a method that reads data using SqlDataReader and yield returns an IEnumerable, e.g.:
IEnumerable<string> LoadCustomers()
{
using(SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
yield return rdr.GetString(0);
}
}
}
Now let's assume I need only newest 10 customers. I could do
LoadCustomers.Take(10)
or pass 10 as a parameter to sql and make my sql
SELECT TOP 10 FROM Customers ORDER BY CreationDate DESC
According to this post the entire results set are being transmitted from sql server to the client even if the datareader reads only few rows (as long as the connection is open) - should I avoid the Take(10)
approach because of that extra data being transmitted anyway to client or it would be a premature optimization to avoid it (because the yield return code would close the connection after it read 10 rows and then the data transmission would stop anyway)?