Why do you parse strings in a LINQ expression? The whole point of LINQ is to avoid this.
var q = from p in this.repository.GetQueryable<Party>() select p; if (startDate.HasValue || endDate.HasValue) { var searchStartDate = startDate.HasValue ? startDate.Value : DateTime.MinValue; var searchEndDate = endDate.HasValue ? endDate.Value : DateTime.MaxValue; return q.Where (p=> p.Date >= searchStartDate.ToUniversalTime() && p.Date <= searchEndDate.ToUniversalTime()).ToList(); } return q.ToList();
UPDATE: In response to the comments: I create this at runtime. The question is not at run time, but at compile time; it is "in lines" and "in code." StringBuilder allows you to add text; LINQ allows you to connect lamps. It all works the same way: except for your code, the type and syntax checked with lambdas are safe.
To demonstrate this concept again, the following code compiles and works fine, and allows you to modify the Where clause based on the oddsOnly and lowerLimit .
int[] nums = {1,2,3,4,5,6,7,8,9,10}; bool oddsOnly = true; bool lowerLimit = 5; var q = from i in nums select i; if (oddsOnly) q = q.Where( n=> n%2 == 1); if (lowerLimit != 0) q = q.Where( n=> n >= lowerLimit); foreach(var i in q) Console.WriteLine(i);
Depending on how you set these values, it will use zero, one or both where clauses.
source share