Search code examples
c#linqdynamicsystem.linq.dynamic

System.Linq.Dynamic and DateTime


I am using System.Linq.Dynamic to do custom where clauses from an ajax call in .Net MVC 1.0.

It works fine for strings, int etc but not for DateTime, I get the exception cannot compare String to DateTime. The very simple test code is

items = items.Where(string.Format(@" {0} > {1}{2}{1} ", searchField, delimiter, searchString));

Where searchField will be for example start_date and the data type is DateTime, delimiter is " (tried with nothing as well) and searchString will be 01-Jan-2009 (tried with 01/01/2009 as well) and items is an IQueryable from LinqToSql.

Is there a way of specifying the data type in a dynamic where, or is there a better approach. It is currently already using some reflection to work out what type of delimiter is required.


Solution

  • I think that you can convert the searchString to a DateTime and pass it in as a parameter to the dynamic where method itself.

    itmes = items.Where( string.Format( "{0} > @0", searchField ),
                         DateTime.Parse( searchString ) );