System.Linq.Dynamic and DateTime

12.5k Views Asked by At

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.

5

There are 5 best solutions below

1
On BEST ANSWER

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 ) );
0
On
yourlist.Where("PostDate > DateTime(2013, 07, 24)");
2
On

I used Convert.ToDateTime to solve the issue, as I am doing something similar to Kappasims

items = items.Where(string.Format("{0} > Convert.ToDateTime(\"{1}\")", searchField, searchValue); 
0
On

If you want to do this with just the Where([string]) format, not passing in other paramaters, you can use the date format Date(yyyy, mm, dd). So I was able to get this working by doing

items.Where("DateAdded > Date(2013, 06, 18)")

There is a full spec here that outlines the parsing and valid uses.

0
On

What if the entire lambda is being created dynamically (we'll go with equals instead of greater than) and the type is not known? In that case you can't use DateTime.Parse in the where parameters. If you try to pass in the DateTime object, Dynamic LINQ interprets it as an int32 type. Could you possibly do it by converting the ticks or milliseconds of the DateTime first and comparing that?