我有一个具有日期时间字段的表。有多行,各种各样,有时相同的日期。
我正在尝试找到一个LINQ查询,它可以在最后 n 天返回给我一个IList的所有条目,但是对于返回的每一行,我应该只看到来自的行最长时间。
e.g。如果我在一天中有4/4/16 1:00:00和4/4/16 2:00:00的行,我希望检索后一个日期的所有行。
补充说明:
实体有一个属性,让我们说类别。我希望查询返回ONE IList,其中填充了按最大日期PER DAY和PER CATEGORY排序的每个实体。 e.g。
Item1 | Category1 | 10/10/2016 11:00:00
Item1 | Category1 | 10/10/2016 11:00:00
Item1 | Category1 | 10/10/2016 11:00:00
Item1 | Category2 | 10/10/2016 11:00:05
Item1 | Category1 | 10/10/2016 11:00:05
Item1 | Category1 | 10/10/2016 11:00:05
Item1 | Category2 | 10/11/2016 11:00:00
Item1 | Category1 | 10/11/2016 11:00:00
我希望结果看起来像一个列表:
Item1 | Category2 | 10/10/2016 11:00:05
Item1 | Category1 | 10/10/2016 11:00:05
Item1 | Category1 | 10/10/2016 11:00:05
Item1 | Category2 | 10/11/2016 11:00:00
Item1 | Category1 | 10/11/2016 11:00:00
答案 0 :(得分:1)
var n = new DateTime(2016, 10, 10);
var res = from data in list
where data.Date >= n
group data by new { data.Date.Year, data.Date.Month, data.Date.Day }
into dataGroup
select dataGroup.OrderBy(eg => eg.Date).Last();
这是一个小例子:
class Data
{
public string Name { get; set; }
public DateTime Date { get; set; }
}
static void Main(string[] args)
{
var list = new List<Data> {
new Data() { Date = new DateTime(2016, 10, 9, 11, 0 , 0) },
new Data() { Date = new DateTime(2016, 10, 10, 11, 0 , 0) },
new Data() { Date = new DateTime(2016, 10, 10, 13, 0, 0) },
new Data() { Date = new DateTime(2016, 11, 10) },
new Data() { Date = new DateTime(2016, 11, 11, 10, 0, 0) },
new Data() { Date = new DateTime(2016, 11, 11, 9, 0, 0) },
};
var n = new DateTime(2016, 10, 10);
var res = from data in list
where data.Date >= n
group data by new { data.Date.Year, data.Date.Month, data.Date.Day }
into dataGroup
select dataGroup.OrderBy(eg => eg.Date).Last();
foreach (Data r in res.ToList())
{
Console.WriteLine(r.Date);
}
Console.ReadKey();
}
输出:
10/10/2016 1:00:00 PM
11/10/2016 12:00:00上午
11/11/2016 10:00:00 AM
答案 1 :(得分:1)
我正在尝试查找一个LINQ查询,该查询可以在过去n天返回给我一个所有条目的IList,但对于返回的每一行,我应该只看到来自最长时间。
然后您需要过滤最后 n 天数据,按日期分组,在每个日期内找到最长时间,选择所有行在最长时间的日期内,最后压扁结果:
var endTime = DateTime.Today; // uncomment to include today .AddDays(1);
var startTime = endTime.AddDays(-n);
var result =
from e in db.Table
where e.DateTime >= startTime && e.DateTime < endTime
group e by e.DateTime.Date into dateGroup
let maxTime = (from e in dateGroup select e.DateTime).Max()
from e in dateGroup
where e.DateTime == maxTime
select e;
答案 2 :(得分:0)
尝试此操作,假设n
为int
代表最后 n
天。
DateTime sinceLast = DateTime.Now.AddDays(-n);
DateTime sinceLastAtMidnight = new DateTime(sinceLast.Year, sinceLast.Month, sinceLast.Day);
var result = lstDate.Where(x => x >= sinceLastAtMidnight)
.Select(x => new
{ DateActual = x,
DateWitoutTime = new DateTime(x.Year, x.Month, x.Day)
})
.GroupBy(x => x.DateWitoutTime)
.Select(x => x.OrderByDescending(y => y.DateActual).FirstOrDefault())
.Select(x => x.DateActual)
.ToList();