Linq for dates that is dynamic

asp.net dynamic-linq linq

Question

I want to create a dynamic Linq. Here is my code, which is good for a single date. However, the user has a wide range of calendar options. And I must create Linq for each of the chosen 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 can this query be updated?

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

Popular Answer

The predicate for your where clause must be constructed dynamically.

Watch the predicatebuilder, please.

EDIT

PredicateBuilder allows this becauseAND and OR operators.

If usingOR You must begin with the default value ofFalse :

// 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