1

I have a problem. I want to build a dynamic LINQ query like this:

 var result = from li in datacTx.LIs
                     where 
                           (((StartDate != null) && (StartDate.Date != DateTime.MinValue)) ? li.Available <= StartDate.Date : true) &&
                           (((EndDate != null) && (EndDate.Date != DateTime.MinValue)) ? li.Expire <= EndDate.Date : true)
                     select new
                         {
                             A,
                             B,
                             C,
                             D
                         };

Before calling this query I am intializing the StartDate and EndDate with:

        StartDate = DateTime.MinValue;
        EndDate = DateTime.MinValue;

The problem is that the branch of "if" is always wrong I never can get the "true" branch if the StartDate and EndDate are having MinValue.

4

1 回答 1

1

尝试使用更简单的条件:

where ((StartDate == DateTime.MinValue || li.Available <= StartDate.Date) &&
       (EndDate == DateTime.MinValue || li.Expire <= EndDate))

但是,如果我要实现这样的东西,我实际上会动态创建查询:

var query = datacTx.LIs;
if(StartDate != DateTime.MinValue)
    query = query.Where(li => li.Available <= StartDate.Date);
if(EndDate != DateTime.MinValue)
    query = query.Where(li => li.Expire <= EndDate .Date);

var result = query.Select(x => new { A, B, C, D });
于 2013-07-18T19:39:31.877 回答