2008/07/11

Wrapping statements

Many people (me also) like to wrap many statements into a single statement so that it looks short and clean. However, it's not a good idea in the following LINQ to SQL query:
string[] names = { "Jim", "John", "Kenny", "Mary", "Jay" };

IEnumerable<string> query = 
from n in names
where n.Length == names.Max(n1 => n1.Length)
select n;  //the output is Kenny
This query is not so efficiency because the subquery is recalculated on each outer loop and will create one more round trip to the database each time. We can improve it by separating the subquery like this:
int max = names.Max (n => n.Length);

IEnumerable<string> query = 
from n in names
where n.Length == max
select n;


PS: If you want to understand more, please refer to the C# 3.0 in a nutshell.

No comments:

Post a Comment