开发者

LINQ query records based on date array

I have a table (I am using Entity Model) and filtered that table using LINQ query which is working fine. Now I want to filter the records on the basis of array of dates. I am not able to implement IN clause on array of dates

filteredList = leadsNewAndScheduled.Where(lead =>  
              (LeadTypeIDs.Contains(lead.TYPE_ID.ToString()) ||
              LeadTypeIDs == string.Empty) &&
              (priorityIDs.Contains(lead.PRIORITY_ID.ToString()) ||
              priorityIDs == string.Empty) &&
  开发者_运维知识库            (((lead.EXPIRED_ON <= dateExpiry ||
              Convert.ToDateTime(lead.EXPIRED_ON) == DateTime.Today.Date) &&
              lead.STATUS_ID == (int)Enumerations.LeadStatus.New) ||
              lead.STATUS_ID == (int)Enumerations.LeadStatus.Active) &&
              (lead.START_TIME IN (arrAppointmentDates))
            ).ToList();

I want your help in following

(lead.START_TIME IN (arrAppointmentDates))

Thanks in advance.


Use Predicate Builder

Write your query without the date condition like

var query = leadsNewAndScheduled.Where(lead =>  
              (LeadTypeIDs.Contains(lead.TYPE_ID.ToString()) ||
              LeadTypeIDs == string.Empty) && ....

Then write

  var predicate = PredicateBuilder.False<Lead>();

  foreach (DateTime date in dates)
  {
    DateTime temp = date;
    predicate = predicate.Or (p => p.START_TIME == temp);
  }

  var result = query.Where(predicate).ToList(); // Don't call ToList() earlier

However please note that if you're using Entity Framework you need to call AsExpandable() on the entity set before applying predicates on it like so:

return objectContext.Products.AsExpandable().Where (predicate);


I solved this problem while declaring list of dates and then applying contains clause in LINQ query.

example:

//list of dates.
List<DateTime> arrAppointmentDates;

//change in query
arrAppointmentDates.Contains(Convert.ToDateTime(lead.START_TIME).Date)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜