I think, you're confusing lambda and LINQ. Lambda functions are not lazy evaluated. They are simply delegates (or anonymous functions). You can even invoke a lambda function asynchronously. But, these are irrelevant to lazy evaluation. For LINQ case, lazy evaluation is "must-have". Because, you can add queries on queries. So, at data reading, they have to be evaluated to simplify LINQ queries to actual data queries (say SQL). To make it clear, here is "real" product "LINQ to SQL" code from our applications:
Originally Posted by m^2
This code does not execute any single line of SQL code. It accumulates LINQ queries over and over again by given filtering parameters. If you want to fetch data you can just simply call "query.ToArray()" to compile LINQ query into SQL on demand. As to overhead, it's very little today with service packs. At first times, it was damn slow comparing to precompiled queries.
private static IQueryable<UdtProject> BuildQuery(ModuleDataContext context,
int companyID, int engineerID, int cityID, int countyID, string approvalState)
var query = from x in context.UdtProjects select x;
if (companyID > 0)
query = from x in query where x.CompanyID == companyID select x;
if (engineerID > 0)
query = from x in query where x.EngineerID == engineerID select x;
if ((cityID > 0) && (countyID < 0))
query = from x in query where x.County.CityID == cityID select x;
if (countyID > 0)
query = from x in query where x.CountyID == countyID select x;
UdtProjectApprovalState state = ObjectParser.ParseEnum<UdtProjectApprovalState>(approvalState);
query = from x in query where x.ApprovalState == state.ToString() select x;
Here is the code that calls the above code. Note that until "ToArray()", it's still not evaluated.
using (ModuleDataContext context = new ModuleDataContext(CmsHelper.ConnectionString))
var query = BuildQuery(context, companyID, engineerID, cityID, countyID, approvalState);
return (from x in query
orderby x.CreationTime descending,
"Equals()" are used for reference equality by default. In intellisense tip, description is clear to me. It compares references not actual data. If you want to compare containing data, there is a IEquatable interface for such usages (you have to implement that interface for your objects). If you want to extend this "comparing containing data" feature to all objects, you can still write a simple extension method which invokes reflection to compare arbitrary classes' containing data.
Originally Posted by m^2
I think, you make some assumption before using a method and that causes to pull you into trouble. Fastest way could be just read intellisense tip.