RSS

LINQ and Dynamic Query – Comparing DateTime value

10 Mar

By: lakswin

In one of our development, we end up with the situation that needs to check the DateTime value in Dynamic LINQ query. Trying different ways out there and googling a bit, finally got some useful references that helped us to resolve the same

Hope, you would love reading!

 

Example:

TestEntities te = new TestEntities();

string dateString = “12/01/2010″;

 

Used the following overload for “.Where” :

# 1:

IQueryable<T>.Where(Expression<Func<State, bool>> predicate)

var dateTest = te.SiteLogs

.Where(String.Format(“it.TimeStamp >= DATETIME ‘{0}’”, Convert.ToDateTime(dateString).ToString(“yyyy-MM-dd HH:mm”)))

.Select(“it.IPAddress”);

 

# 2:

IQueryable.Where(string predicate, params object[] values)

var dateTest1 = te.SiteLogs

.Where(“it.TimeStamp >= @0″,  Convert.ToDateTime(dateString))

.Select(“it.IPAddress”);

 

Observations:

In # 1,

  • We need to say the “Time” format also, that is compulsory. Otherwise it would throw an error as well.  And again, the syntax with “DATETIME” is wired 🙂
  • The resultant date format should be “yyyy-MM-dd “

 

In # 2,

Its clean and simple. I like this syntax. Here you can add any number of Params like @0, @1 & so on

 

References:

http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

http://msdn.microsoft.com/en-us/library/bb399176.aspx

 

Copy from: https://lakswin.wordpress.com/2011/10/20/linq-and-dynamic-query-%E2%80%93-comparing-datetime-value/

Advertisements
 
Leave a comment

Posted by on March 10, 2015 in C#, LinQ

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: