开发者

Dynamic Linq for dates

I want to build dynamic Linq. Following is my code which works fine for one date. But use开发者_JS百科r can select many dates from calendar. And I need to make Linq for all those selected dates.

saleDate = calendarSales.SelectedDate;
List<SaleDetails> saleDetials = new List<SaleDetails>();
saleDetials = GetSaleDetails();
saleDetials.Where(sale => (Convert.ToDateTime(sale.DATE_TIME).Day == saleDate.Day &&
                           Convert.ToDateTime(sale.DATE_TIME).Month == saleDate.Month && 
                           Convert.ToDateTime(sale.DATE_TIME).Year == saleDate.Year)
                  ).ToList();

How to update this query?


You have to build the predicate for your where clause dynamically.

Take a look at the predicatebuilder.

EDIT

Of cause PredicateBuilder supports AND and OR operators.

When using OR you have to start with the initial value of False:

// building the predicate
var pred = PredicateBuilder.False<SaleDetails>();
foreach (var date in MyDateList) 
{
    pred = pred.Or(sale => sale.DATE_TIME.Date == saleDate.Date);
}

// finally get the data and filter it by our dynamic predicate
List<SaleDetails> saleDetails = GetSaleDetails().Where(pred).ToList();


I'm not sure you need dynamic LINQ here. You should be able to check Where the sale matches Any of the selected dates, like so:

var saleDates = GetSelectedDate();

List<SaleDetails> saleDetials = new List<SaleDetails>();
saleDetials = GetSaleDetails();
saleDetials.Where(sale => saleDates.Any(date => 
   (Convert.ToDateTime(sale.DATE_TIME).Day == date.Day &&
    Convert.ToDateTime(sale.DATE_TIME).Month == date.Month && 
    Convert.ToDateTime(sale.DATE_TIME).Year == date.Year)
    )).ToList();

or checking on the Date property:

var saleDates = GetSelectedDate();

List<SaleDetails> saleDetials = new List<SaleDetails>();
saleDetials = GetSaleDetails();
saleDetials.Where(sale => saleDates.Any(date => 
   Convert.ToDateTime(sale.DATE_TIME).Date == date.Date)).ToList();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜