如何在C#中使用Dynamic Linq设置DateTime equals方法?

时间:2019-08-22 21:45:32

标签: c# linq datetime equals dynamic-linq

我需要通过DateTime字段使用动态LINQ过滤数据。

我正在尝试这样做:

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

但是查询返回零记录。但是,如果我设置了比较方法>=<=而不是==,则查询会返回所需的记录量。
也许我做错了吗?

更新:
我在这里找到了示例:https://stackoverflow.com/a/26450835/7760805,但我仍在寻找更好的解决方案。

更新
由Stef Heyenrath解决。

3 个答案:

答案 0 :(得分:3)

您应该将字符串传递到MyMethod方法中,然后转换为DateTime并删除该方法中的毫秒数。

publication_title    authors                             author          type ...
title 1              ['author1', 'author2', 'author3']   author1         proceedings
title 1              ['author1', 'author2', 'author3']   author2         proceedings
title 1              ['author1', 'author2', 'author3']   author3         proceedings
title 2              ['author4', 'author5']              author4         collections
title 2              ['author4', 'author5']              author5         collections
title 3              ['author6', 'author7']              author6         books
title 3              ['author6', 'author7']              author7         books
.
.
. 

答案 1 :(得分:3)

根据所需的精度,您可以将>=<运算符一起使用,如下所示:

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

答案 2 :(得分:-1)

MyMethod的内容是什么?

尝试使用$字符串构建器。

MyMethod($"datetime_field == {new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute , dt.Second)}");

OR

MyMethod($"datetime_field == {dt.ToString())}");

我认为这与您的逻辑有关,而不是您如何构造或传递datetime参数。