Reputation: 61
I need to filter data with Dynamic LINQ by DateTime field.
I'm try doing this like:
public class MyClass
{
private DateTime datetime_field;
//...
//some other fields
//...
}
public void MyMethod(string where_clause)
{
List<MyClass> myData = new List<MyClass>()
{
//...
//initialization
//...
};
var query = myData.Where(where_clause).ToList();
myDataGridView.DataSource = query;
}
// usage
string value = DateTime.Now.ToString(); // for example
if (DateTime.TryParse(value, out DateTime dt))
MyMethod("datetime_field == DateTime(" + dt.Year + ", " + dt.Month + ", " + dt.Day + ", " + dt.Hour + ", " + dt.Minute + ", " + dt.Second + ")");
But the query return zero records. But if i set compare method >=
or <=
instead ==
, query returns needed records amount.
Maybe I'm doing something wrong?
UPDATE:
I found example here: https://stackoverflow.com/a/26450835/7760805, but I'm still search a better solution.
UPDATE:
Solved by Stef Heyenrath.
Upvotes: 0
Views: 1588
Reputation: 9860
Depending on the accuracy you need, you could just use the >=
and <
operators together, like this:
var date = DateTime.Now;
// accuracy is 1 day in this example
var from = date.Date;
var to = from.AddDays(1);
// If you only need to select on a day, use this:
var result = query.Where("datetime_field >= @0 && datetime_field < @1", from, to);
Upvotes: 3
Reputation: 2310
You should pass a string into the MyMethod method, then convert to DateTime and remove milliseconds within the method.
public class MyClass
{
public DateTime datetime_field; // note this needs to be public, not private
}
public void MyMethod(string strDate)
{
if (DateTime.TryParse(value, out DateTime dt))
{
List<MyClass> myData = new List<MyClass>()
{
// initialization
};
var roundedDate = new DateTime(dt.Year, dt.Month, dt.Day,
dt.Hour, dt.Minute, dt.Second);
var query = myData.Where(obj => obj.date_time == roundedDate).ToList();
myDataGridView.DataSource = query;
}
}
// usage
string value = DateTime.Now.ToString();
MyMethod(value);
Upvotes: 3
Reputation: 594
What is the content of MyMethod ?
Try using the $ string builder.
MyMethod($"datetime_field == {new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute , dt.Second)}");
OR
MyMethod($"datetime_field == {dt.ToString())}");
I think its a problem with your logic not how you are constructing or passing datetime parameter.
Upvotes: -1