Question

Let's say I have these two entities :

  • Document, which contains a DateTime property (called Date).
  • Period, which contains two DateTime properties (called DateFrom and DateTo) that represents a period of time.

Then, consider this expression, in which d represents a Document and p represents a Period, that is used to filter a Document collection to return only those who are part of a given Period :

d => d.Date >= p.DateFrom && d.Date <= p.DateTo

The problem is, given a collection of Period entities, how could I build a lambda expression which represents a concatenation of multiple expressions like the above expression, so it gives :

d => 
     (d.Date >= p1.DateFrom && d.Date <= p1.DateTo) 
  && (d.Date >= p2.DateFrom && d.Date <= p2.DateTo) 
  && (d.Date >= p3.DateFrom && d.Date <= p3.DateTo) 
  && ...

I want the result to be a lambda expression that I can further combine to other conditions before filtering my Document collection.

Était-ce utile?

La solution

var documentsInAllPeriods = documents.Where(d => periods.All(p => 
    d.Date >= p.DateFrom && d.Date <= p.DateTo));

(Note you can change All to Any if you want the documents in any period rather than the documents in every period.)

Autres conseils

Assuming the collection of period entities (periods) is available for the lambda expression:

(d) => 
{ 
   bool cond = false;
   foreach(Period p in periods)  
   {
      // check period
      // return earlier if condition not met
   }

   return cond;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top