Reputation: 301
Have a small problem with LINQ queries.
Basically I have two lists, filled with dates.
List<DateTime> start = GetListOfStartDates();
List<DateTime> end = GetListOfEndDates();
DateTime date = new DateTime(2012, 1, 1);
How do I perform a LINQ query, where I compare a date against the start and end date, basically in sense:
(start <= date && end >= date)
Obviously I understand that they are lists, so this does not work, how do I compare a single date against two lists of dates? Basically doing a between for a set of dates.
The start indices will always match end indices, start[7]
will always match end[7]
. I'm attempting to turn a mysql between
-query into LINQ. So I'm looking for IF the given "date" is within any start-end pair.
Upvotes: 1
Views: 314
Reputation: 100366
Another interpretation of OP's goal:
bool b = start.Zip(end, (x, y) => new { Start = x, End = y })
.Any(z => z.Start <= date && z.End >= date);
Or you can use All()
instead, that depends on your logic.
Upvotes: 3
Reputation: 3302
Assuming I'm interpreting your question correctly (see my comment above) I think you are better off doing this as a for loop instead of a LINQ query. I'd do something like this:
public bool DateFallsInRange(IEnumerable<DateTime> startDates, IEnumerable<DateTime> endDates)
{
for (int index = 0; index < startDates.Count; index++)
{
if ((startDates[index] <= compareDate) && (compareDate <= endDates[index])) return true;
}
return false;
}
Upvotes: 2
Reputation: 7639
the start and end list index must be the same? Example:
start|end
[0]1940|1950
[1]1890|1930
the date 1931 should pass because 1890<1931<1950? or should not pass because 1931<1940 and 1931>1930?
Upvotes: 0