How to set DateTime equals method with Dynamic Linq in C#?

c# datetime dynamic-linq equals linq

Question

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.

1
0
8/23/2019 7:36:52 PM

Accepted Answer

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);
3
8/23/2019 7:19:33 PM

Popular Answer

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);


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow