Linq for dates that is dynamic

asp.net dynamic-linq linq

Question

I want to build dynamic Linq. Following is my code which works fine for one date. But user 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?

1
0
9/28/2011 9:25:02 AM

Popular Answer

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();
2
9/28/2011 10:35:43 AM


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