How do I filter a LINQ query by date?

query = query.Where(q => q.Date.ToString().Contains(strDate));

      

The above operator is invalid.

If I use "==" then it matches the exact date. Everything is good. but can i filter, How do we filter rows ??

0


a source to share


3 answers


I don't understand what you mean by "filter".

You can do things like:

query = query.Where(q => q.Date.Year.Equals(myDate.Year));

      

or



query = query.Where(q => q.Date.Day.Equals(myDate.Day));

      

if you need it.

Of course you need to overlay strDate on DateTime. If you really don't want to do this, you can also cast the DB date to a string of the same format:

query = query.Where(q => q.Date.ToString("dd-MM-yyyy").Contains(strDate));

      

+3


a source


Assuming q.Date is a DateTime instance, I don't think converting a DateTime instance to String is the best way to compare dates. It would be much more reliable to filter DateTime based on object properties. For example, Year, Month, etc.

For example, if you want to filter the year in strDate, you can do the following.



var d = DateTime.Parse(strDate);
query = query.Where(q => q.Date.Year == d.Year);

      

Can you give us more context detailing what type of strDate values ​​this way will hold, we can know what you want to filter with.

0


a source


If you are confident in the string that you get in your search, then you can always do something specific for your region.

(((q.Date == null ? DateTime.Parse("01/01/1900") : q.Date).Value.Day.ToString()) + "/" + ((q.Date == null ? DateTime.Parse("01/01/1900") : q.Date).Value.Month.ToString()) + "/" + ((q.Date == null ? DateTime.Parse("01/01/1900") : q.Date).Value.Year.ToString())).ToString().Contains(strDate) || (q.Date == null ? DateTime.Parse("01/01/1900") : q.Date).ToString().Contains(strDate))

      

This will result in a match against a string d/m/yyyy

that would have been checked, for example in a date. It's not ideal for public searches, but better than simple searches .ToString().Contains()

.

0


a source







All Articles