I have a list of dates. I would like to query the list and return a list of pairs where the first item is a date and the second is the date which occurs just before the first date (in the list).
I know this could easily be achieved by sorting the list and getting the respective dates by index, I am curious how this could be achieved in LINQ.
I've done 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
                It is easy as converting 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()
    });
                        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 });
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With