문제

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.

도움이 되었습니까?

해결책

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.)

다른 팁

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;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top