LINQ subquery to select a "previous" value in a list

I have a list of dates. I would like to query the list and return a list of pairs where the first element is the date and the second is the date that occurs immediately before the first date (in the list).

I know that this can be easily achieved by sorting the list and getting the corresponding dates by index, I am curious how this can be achieved in LINQ.

I did this in SQL with the following query:

SELECT Date, (SELECT MAX(Date) FROM Table AS t2 WHERE t2.Date < t1.Date) AS PrevDate FROM Table AS t1 
+6
source share
2 answers

It is easy to convert your current query into a LINQ query:

 var result = table.Select(x => new { Date = x.Date, PrevDate = table.Where(y => y.Date < x.Date) .Select(y => y.Date) .Max() }); 
+5
source
 List<DateTime> dates = new List<DateTime>() { DateTime.Now.AddDays(1), DateTime.Now.AddDays(7), DateTime.Now.AddDays(3), DateTime.Now.AddDays(6), DateTime.Now.AddDays(5), DateTime.Now.AddDays(2), DateTime.Now.AddDays(3), }; dates = dates.OrderByDescending(x => x).ToList(); var result = dates.Skip(1) .Select((x, i) => new { Date = dates[i], PreviousDate = x }); 
+2
source

All Articles