[英]Nested LINQ query to select '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 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. 我知道这可以很容易地通过排序列表并通过索引获取相应的日期来实现,我很好奇如何在LINQ中实现这一点。
I've done this in SQL with the following query: 我在SQL中使用以下查询完成了此操作:
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: 将当前查询转换为LINQ
查询很容易:
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 });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.