无法绕过如何完成此链接查询的问题。我希望Foo.Id与每个QueueNumber的最大ProcessingStart和ProcessingComplete相关联
假设:
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 / ProcessingComplete赋值对它们有不同的错误,这些只是我尝试过的两个(不成功)来制作所需的东西。
我提供的数据的预期结果将是:
Queue MaxStartId MaxCompletedId
-----
1 2 1
2 3 3
答案 0 :(得分:2)
你想:
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