Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested LINQ query to select 'previous' value in a list

Tags:

c#

linq

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
like image 511
nswart Avatar asked Feb 14 '13 17:02

nswart


2 Answers

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()
    });
like image 124
RMalke Avatar answered Sep 22 '22 04:09

RMalke


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 });
like image 41
david.s Avatar answered Sep 18 '22 04:09

david.s