具有分组依据和最大日期的Linq查询,获取Id
本文关键字:Linq 日期 查询 Id 获取 | 更新日期: 2023-09-27 18:21:56
我很难理解如何完成这个链接查询。我想获得与每个QueueNumber 的最大ProcessingStart和ProcessingComplete中的每一个相关联的Foo.Id
给定:
public class Foo
{
public int Id { get; set; }
public int QueueNumber { get; set; }
public DateTime? ProcessingStart { get; set; }
public DateTime? ProcessingComplete { get; set; }
}
public class Bar
{
public int QueueNumber { get; set; }
public int MaxStartId { get; set; }
public int MaxCompleteId { get; set; }
}
public class QueryData
{
List<Foo> Foos = new List<Foo>()
{
new Foo()
{
Id = 1,
QueueNumber = 1,
ProcessingStart = new DateTime(2014, 1, 1),
ProcessingComplete = new DateTime(2014, 1, 3)
},
new Foo()
{
Id = 2,
QueueNumber = 1,
ProcessingStart = new DateTime(2014, 1, 2),
ProcessingComplete = null
},
new Foo()
{
Id = 3,
QueueNumber = 2,
ProcessingStart = new DateTime(2014, 1, 1),
ProcessingComplete = new DateTime (2014, 1, 2)
},
};
public void GetMaxProcessingStartCompleteIdPerQueueNumber()
{
List<Foo> foos = Foos;
var query = foos
.GroupBy(gb => gb.QueueNumber)
.Select(s => new Bar()
{
QueueNumber = s.Key,
MaxStartId = s.Select(s2 => s2.Id) // select Id where Id is equal to the max ProcessingStart - Cannot implicitly convert IEnum<int> to int
MaxCompleteId = s.Max(m => m.ProcessingComplete.Value) // select Id where Id is equal to the max ProcessingStart - Cannot implicitly convert DateTime to int
});
}
}
我意识到上面的两个ProcessingStart/ProcessingCOComplete作业有不同的错误,这只是我试图(但没有成功)制定所需的两个作业。
我对所提供数据的预期结果是:
Queue MaxStartId MaxCompletedId
-----
1 2 1
2 3 3
您想要:
MaxStartId = s.First(s1 => s1.ProcessingStart == s.Max(s2 => s2.ProcessingStart)).Id,
MaxCompleteId = s.First(s1 => s1.ProcessingComplete == s.Max(m => m.ProcessingComplete.Value)).Id
这应该有效,但我会使用MaxBy
方法。不为每条记录执行Max
:
MaxStartId = s.MaxBy(s1 => s1.ProcessingStart).Id,
MaxCompleteId = s.MaxBy(s1 => s1.ProcessingComplete).Id